#204 – Three Rules About Using Implicitly-Typed Variables

You can create an implicitly-typed variable using the var keyword.  The type is inferred, rather than declared.

Here are a few additional rules about using implicitly-typed variables.

Rule #1 – You can use var only for local variables

You can’t use var when declaring class fields/properties.

    public class Person
        public var Height;    // Compile-time error

Rule #2 – You must initialize an implicitly-typed variable when you declare it

If you don’t initialize an implicitly-typed variable, the compiler can’t infer the type.

        static void Main()
            var height;   // Error: Implicitly-typed local variables must be initialized

Rule #3 – You must declare implicitly-typed variables one at a time

You can’t declare more than one variable on the same line with var.

        static void Main()
            int i, j, k;   // Declare three int variables

            var x, y, z;   // Error: Implicitly-typed local variables cannot have multiple declarators

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #204 – Three Rules About Using Implicitly-Typed Variables

  1. kai zhou says:

    Nice job, thank you Sean.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: