C# 3.0: Vote for the keyword “var”

You all probably know what is “var”. You might have a question why this new keyword is required in programming language like C#. One of the few strong reasons is to have an Anonymous Type stored in a variable. Whenever you have to initialize a type you have to mention the type before you give a name for a variable. But can you do something like this,

 

AnonymousType~1 obj = new {Id = 1, Name="Wriju"};

The anonymous type will be decided during compile time and it is random. You simple cannot assume anything here. The proper way of declaration would be,

var obj = new {Id = 1, Name="Wriju"};

 

Another area in LINQ where to get multi column output we often use anonymous type and get the IEnumerable of that type. So when you have no type in place can you declare IEnumerable of that type?

 

var q = from c in db.Customers

        select new { c.CompanyName, c.ContactName };

If you want to have IEnumerable<T> then you have to have type T defined in your apps somewhere. But it is very inconvenient to have a type defined every time you want to get a different combination.

 

Things to remember,

Ø var cannot be used as public property/field

Ø var cannot be a return type of any method

 

Otherwise var rocks and it is Reflection enabled. Performance is equal.

 

Namoskar!!!