Implicitly Typed Local Variables in VS2008 and C# 3.0

.NET Musings

Wandering thoughts of a developer, architect, speaker, and trainer

NAVIGATION - SEARCH

Implicitly Typed Local Variables in VS2008 and C# 3.0

Technorati Tags: ,,,

Another new feature in VS2008 and C# 3.0 that compiles down to 2.0 compatible IL is implicit typing of variables. This allows the use of the "var" keyword as the declared type.  (Strictly speaking, "var" is not a true keyword.  It is interpreted as a keyword when it is used in the place of a type.)  This is not the same as week typing - as described in this post, the variables are still strongly typed.

All of the following constructs are perfectly legal:

  1: var myString = "s";

  2: var myInt = 0;
  3: var myDecimal = 0.0M;
  4: var myIntArray = new[] { 1, 2, 3, 4, 5 };
  5: var myDouble = 0.0D;

Note the explicit declaration (via the "M") for the decimal value.  The compiler assumes that 0.0 is a double, and will not type it as a decimal.  Unless of course you have code like this:

  1: var myDecimal = 0.0M;
  2: var myDecimal2 = myDecimal + 2;

This is where implicit typing falls short, and deals a serious blow to readability.  To someone else reading your code, there is much too much thought that needs to go into some of these declarations, and last I checked the Lezinski-Reddick naming convention is passe.


So why use them?  They are truly a side effect of the Linq additions to the framework, and are invaluable in that context. Outside of that, the one place I would consider using them are in iterators.

  1: foreach (var i in myIntArray)
  2: {
  3:     //Do something
  4: }

Certainly not a woo-hoo moment, but usable AND readable.  So, think before you act, and as we said in college, temper your actions with wisdom.


Happy Coding!

Comments are closed
Managed Windows Shared Hosting by OrcsWeb