Thursday, January 15, 2015

How var type is different from anonymous type


Ans. var- var data type was introduced with C# 3.0. It is used to declare implicitly typed local variable means it tells the

compiler to figure out the type of the variable at compile time. A var variable must be initialized at the time of declaration.

For Example: var i = 20; // implicitly typed int i = 20; //explicitly typed var str = "1"; //declaration and initialization var num = 0; string s = "string"; //explicitly typed var s2 = s; // implicitly typed

Basically, var is an anonymous type, hence use it whenever you don't know the type of output or it is anonymous. Suppose you are

joining two tables and retrieving data from both the tables then the result will be an anonymous type since data will come from both the tables.

Expression assigned to var must be executed at compile time to know the type of output, so that var type may behave like the new type assigned to it.

DataContext context =
new DataContext();
var q =
(from e in context.Employee join d in context.Department on e.DeptID equals d.DeptID
select new { e.EmpID, e.FirstName, d.DeptName, d.DeptLocation });



Anonymous Type- An anonymous type is a simple class generated by the compiler within IL to store a set of values. var data type and new keyword is used to create an anonymous type.
var emp = new { Name = "Deepak", Address = "Noida", Salary = 21000 };
At compile time, the compiler will create an anonymous type, as follows:



class __Anonymous1
{ private string name;
 private string address;
int salary;
 public string Name { get { return name; } set { name=value } }
 public string Address { get { return address; }
 set { address = value; } } public int Salary { get { return salary; }
 set { salary = value; }
}
}



The anonymous type is very useful when you want to shape the result in your desired form like this:


DataContext context = new DataContext();
 var result = from book in context.Books where book.Price > 200 orderby book.IssueDate
 descending
select new { Name = book.Name, IssueNumber = "#" + book.Issue };

In above example, I change the name of the “Issue” field of Book table to “IssueNumber” and add # before value to get desired output.


No comments:

Post a Comment