Saturday, 19 May 2012

Anonymous Types in C#

Anonymous Types are set of public properties without including types explicitly,they are read-only in C#.
They must be declared with var keyword. All properties must be initialized.

Example 1
var objAnyo= new { Name = "seethapathi", Age = 28, city = "Hyderabad", Country = "INDIA" };

Console.WriteLine( objAnyo .Age.GetType()); //returns System.Int32
Console.WriteLine( objAnyo .Name.GetType()); //returns System.String etc.,

type of the variables are determined at compile time itself. var keyword tells the compiler to use "type inference(automatic detection of type)".

objAnyo .Age = 31;

gives compiler error

 Error 1 Property or indexer ' objAnyo  #1.Age' cannot be assigned to -- it is read only c:\users\administrator\documents\visual studio 2010\Projects\ConsoleApplication4\ConsoleApplication4\Program.cs 15 13

Example 2
  Anonymous types are useful in LINQ

var customer =  from c in  customers
                            select new {c.CustomerID,c.City}

here c.CustomerID,c.City  are 2 properties for anonymous type customers.
c.CustomerID,c.City types  are same as in customers

Note: returning subset of elements(as shown in Example 2) is also called anonymous types.