Monday, 6 August 2007

Local Variable Type Inference

This is a great little feature which is now available in C# 3.0.

Local Variable Type Inference allows you declare a strong typed variable without specifying the type.

For Example:


var myList = new List<string>{"Hello", "World"};

At first I was a little sceptical about this feature. As any good programmer knows it is better and cleaner to know your types etc. From reading the code its not always obvious what the type of the variable is.

However this is nice in theory but in practise it is absolutely sweet, and saves you verbose local declarations.

There are some key points to note:


  • This is NOT equivalent to using a late bound object

  • Local Variable Type Inference is equivalent to typing the full declaration yourself (the C# compiler will perform the subsitution for you).

  • You must initialise with a value (e.g. var myString = "Hello";) so the compiler can infer the type. You cannot skip initalisation (e.g. var myString;) as this will produce a compiler error.

  • You cannot switch types (i.e. initialise with a string, and then assign an integer, you must follow the same rules as fully declared types as they are equivalent)

  • You can only use Local Variable Type Inference for a locally declared variable scoped within a method (as the name might suggest




As I say although I initially had reservations about this feature, I find that when you are using enumarable types, or just instatiating an object with a large declaration (dictionaries etc), using the var keyword is more readable than double declarations.

Finally thanks to Daniel Moth for helping me out with my worst subject (whioh is giving things the correct name, Doh!)

Next post will be on Anonymous Types (and what they actually are)

2 comments:

Daniel Moth said...

It looks like you are confusing the names of two features.

What you describe is call Local Variable Type Inference.


Anonymous Types is something different:
http://www.danielmoth.com/Blog/2007/02/anonymous-types-in-c-30-and-vb9.html

HTH

chrishayuk said...

Thanks Daniel,

You are absolutely right.

I get very confused with names.

I will publish a new entry on Anonymous Types and will reference your article.

Thanks Again