#183 – Use var to Tell the Compiler to Figure out the Type

You can use traditional strong-typing in C#, where you explicitly declare the type of every variable.  Or you can use the dynamic keyword for dynamic typing, where data is only type-checked at run-time, rather than compile-time.

You can also use the var keyword when declaring variables.  When you use var, you don’t have to explicitly specify the type–the compiler will figure out the correct type at compile-time.  You’re still using strong-typing in this case, because the type checking is done at compile-time.

The following example still fails to compile.  The compiler figures out that s is of type string, it does type-checking and then complains that the use of Concat is invalid.

            var s = "Sean";
            s = s.Concat(" Sexton");

In the next example, we don’t bother to declare the exact types.

            var s = "Hemingway";
            var backwards = s.Reverse();

            // string
            Console.WriteLine(s.GetType());

            // System.Collections.Generic.IEnumerable<char>
            Console.WriteLine(backwards.GetType());
Advertisements