Anonymous Types in C#

This was introduced in C# 3.0.

Anonymous types are on the fly classes or unnamed classes.

For example i define a class with the following :

class Employee
        private int _EmpID;
        private string _EmpName;
        public int EmpID
                return _EmpID;
                _EmpID = value;
        public string EmpName
                return _EmpName;
                _EmpName = value;


Here’s how i create an object

 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 .

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

Here’s how i use the Anonymous type

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 .

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 .

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

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

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

The type name here i got were different .

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses

  1. Anonymous Types in C# and VB.NET August 2, 2011 Reply

Leave a Reply


Interesting BlogPosts to read

How to get an Enumerator from range of elements from ArrayList in C# ?
The code snippet shown in this blog post demonstrates how you can get the enumeraor from a range of ...
How to check for the column name in an SqlDataReader Object in C# ?
When working in ADO.NET for data access , there are times when you want to check to see if a column ...
How to convert Array to List in C#?
Want to convert array of strings to List of strings in C# ? . Below is a sample code to illustrate t...