#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: #204 – Three Rules About Using Implicitly-Typed Variables « 2,000 Things You Should Know About C#

  2. Pingback: #803 – Situations When You Might Use the var Keyword | 2,000 Things You Should Know About C#

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: