You are on page 1of 2

Anonymous Types in C#

This was introduced in C# 3.0.

Anonymous types are on the fly classes or unnamed classes.

Usage rules/restrictions
The properties in Anonymous types are all read only and therefore cannot be modified
once they are created.
Anonymous types cannot have methods.
Anonymous types are always assigned to vars. This allows the compiler to assign the
right type. But, if Anonymous types are used as return values or as parameters in a
function, they will have to be passed in as Objects, as var is not a proper type

For example i define a class with the following :

class Employee
{
private int _EmpID;
private string _EmpName;
public int EmpID
{
get { return _EmpID;}
set { _EmpID = value;}
}
public string EmpName
{
get { return _EmpName;}
set {_EmpName = value;}
}
}

Heres how i create an object


1 Employee objEmployee = new Employee { EmpID = 1, EmpName = "senthil" };
Note that the properties/ members are initialized here through object initializer .
An object initializer can specify values for one or more properties of an object.
class members such as methods or events are not allowed.
I can also create an object via Implicit type reference .
1 var objEmployee = new Employee { EmpID = 1, EmpName = "senthil" };
Heres how i use the Anonymous type

1 var objEmployee1 = new { EmpID = 1, EmpName = "senthil" };


The actual type of this would be anonymous .
It has no name .
This feature will be extremly be helpful when LINQ is used .

1
The Visual Studio will provide us the full intellisense support for the anonymous type along
with the compile time checking.

Little observations on the anonymous type .


1. I created another anonymous object with the same parameter and when 1 compare the
type of objEmployee1 , objEmployee2 , they are same in the eyes of the compiler .

1 var objEmployee2 = new { EmpID = 6, EmpName = "trivium" };


2. I tried changing the order of the parameters of objuEmployee2.

1 var objEmployee2 = new { EmpName = "trivium",EmpID = 6 };


The type name here i got were different .

You might also like