Friday, June 8, 2012

Anonymous Types in .Net 3.5




Anonymous Types were introduced in .Net 3.5, as the name suggests these types are not per-defined, their type is determined at runtime based on the value which is assigned to it.


The Anonymous Types derive directly from the Object, which makes it flexible enough to accommodate any type assigned to it at runtime.

Anonymous Types 
are created using the var keyword as follows,
var = Any Type

Example

var x = "Hello World"; //Here x Behaves like a String
var x = 10;            //Here x Behaves like an Integer
var x = true;          //Here x Behaves like a Boolean
var x = new list<Employee> ();
//Here x Behaves like a List of type Employee

Anonymous Types, support
IntelliSense, the IntelliSense context menu of type gets populated dynamically based on the value assigned to the type.




Apart from these simple types, Anonymous Types also support creating of complex objects dynamically as follows














Notice that once the Type is created Name and Age have got added to the list of Properties of the new Type x, all this happens dynamically.


Anonymous Types are extensively used in capturing the output of LINQ expressions, to know more on the usage of Anonymous Types in LINQ refer the post Anonymous Types in LINQ.


To know more about LINQ refer the post What is LINQ?

That's it we, have seen the usage of 
Anonymous Types in .Net 3.5





Related Post












Search Flipkart Products:
Flipkart.com

No comments: