C# 3.0 : Useful keyword “var”

People complain about the keyword “var”. Especially, when we use it with the strict programming language like C# in .NET. Developers also complain about the readability part of it. I totally agree with them, but the scenarios where there will be no options but the “var” when it comes to on the fly projection of Language INtegrated Query (LINQ). Can you initialize Anonymous Type without “var”? There are so many no-nos. Let’s appreciate it and start use. I already have explained in one of my previous blogs,

Scenario 1 (Anonymous Type)

+++++++++++++++++++

When you have no type defined but want to create that, we need “var”.

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

You cannot assume the name created by compiler for this Anonymous Type. Please feel free to add comment to my blog if you have choice to add type in the above example while declaring the variable.

Scenario 2 (Projecting it to IEnumerable<AnonymousType>)

++++++++++++++++++++++++++++++++++++++

Suppose if you want to get the output containing only the selected column you have to project it to a type.

IEnumerable<CustomerSelect> query =

from c in db.Customers

where c.City == "London"

select new CustomerSelect

{

CustID = c.CustomerID,

CompanyName = c.CompanyName

};

As you cannot have “,” as you are used to for any T-SQL query. Here you need everything as strongly typed. So you need to create a class, here I have created one,

class CustomerSelect

{

public int CustID { get; set; }

public string CompanyName { get; set; }

}

So here boldly you can retrieve the result like, IEnumerable<CustomerSelect>

in case if you do not want to use var here. But if you are lazy developer like me then you might not be interested in creating class for every need. Rather you will use anonymous type and get the IEnumerable<AnounymousType> as query output. But how will be defining IEnumerable of some anonymous type (in fact no type). No wander you must appreciate the real power of “var” here.

var query =

from c in db.Customers

where c.City == "London"

select new

{

CustID = c.CustomerID,

CompanyName = c.CompanyName

};

Namoskar!!!