Monday, December 3, 2007

Anonymous types: var

Anonymous types are excellent addition to .NET “Orcas” release. These are a convenient language feature that allows developers to write code without bothering about what particular type of object they are dealing with. Anonymous types are declared by var keyword which you most of the times will see in different application of LINQ. It's true it great use with LINQ, but it's not a LINQ feature at all - it's a new language feature.

A very simple use of Anonymous types is (starting with a keyword var):

var helo = 123;


You can assign whatever type you like. But, unlike JavaScript once you assigned one type of value, you cannot assign to other types like this:



var helo = 123;
helo = "hello";


Again, unlike JavaScript, you cannot left a declaration unassigned. Do not ever mix up with JavaScript's var and .NET's one.



var helo;   // It won't compile


Take a look at variety of usage of Anonymous types. Enjoy the powerful Visual Studio's great intellisense:



var helo = 123;
Console.WriteLine(helo.Equals(123));

var hello = "hello";
Console.WriteLine(hello.Length);

var helloWorld = new List<string>() { "hello", "world" };
helloWorld.ForEach(delegate(string x) { Console.WriteLine(x); });


If we consider the performance issue, there's no extra footprint on CLR for Anonymous types. Before it goes to CLR's hands, vars are replaced with appropriate type so there's no extra effort for CLR to understand the types:



var hello = "hello";    // exactly same as: string hello = "hello";




Anonymous types are not only appropriate for lazy developers like me, but also have great effective usage in LINQ. I'll cover that one may be later sometime.