0

var in C# ?!! Anonymous Type

by volkanuzun 18. February 2008 09:46

With C# 3.0, the anonymous type is introduced. Keyword "var" helps you to define an anonymous type. Let's start with a simple example.


int i = 5;
var j = 6;
Console.WriteLine("i is {0}, j is {1}", i, j);

As you can see, we did not tell the compiler what "j" is, however the compiler could figure it out from the assignment. Yes, this is a rule, var declerations should be assigned to a variable type to help the compiler understand the type of var. So at the compile time, the compiler changes the type of var to the type that is specified with the assignment. If you compile the above code, and open the ildasm tool to see the il code, you will see that j is an integer.

This also means that you can't have a declaration like:


var k;


"var" is very much usefull in linq, but you dont need to write linq applications to benefit from it, you can use it to simplify your code such as :

List<int>arrInts = new List<int>(); // means exactly the same thing as below
var arrInts2 = new List<int>();

There are some other restrictions upon using var. For example you can't have a global anonymous variable, it has to be local.

There is a very interesting use of var (actually the only time it really makes sense ). Declaring anonymous class types on the fly such as:


var student = new {FirstName="Joe", LastName="Doe", Age=21, Address="Some Address"};
Console.WriteLine(student.FirstName);

So we've just created an object with 4 attributes on the fly, and the compiler could do the type conversions looking at the assignments.

Tags: , ,

Powered by BlogEngine.NET 1.6.0.0
Original Design by Laptop Geek, Adapted by onesoft