Wednesday, June 22, 2011

Anonymous Typed Classes in C#

Introduction
MSDN Definition: Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The name is generated by the compiler and is not available at the source code level or our application cannot access it. The type of each property is inferred by the compiler.
Anonymous types are a new feature introduced with C# 2.0. Anonymous class is class that has no name and it can help us to increase the readability and maintainability of applications by keeping the declarations of variables much close to the code that uses it.
We create anonymous class by using the new keyword and a pair of braces defining the fields and values that we want the class to contain. For example:
myAnonyClassObject = new { Name = "Abhimanyu", Age = 21 };
Above class contains two public fields called Name as I have initialized a string "Abhimanyu" and Age as I have initialized an integer 42. Compiler generates its name and it is unknown to us.
Now think, if we don't know the name of the class then how we will create an object? This is called anonymous class which can't be known.
After all we have one thing in hand; we can define it as variable by using var keyword. var keyword causes the compiler to create a variable of the same type. For example:
var myAnonyClassObject = new {Name = "Abhimanyu", Age = 21};
Now, we can access anonymous class fields by using dot notation. For example:
Console.WriteLine("Name:{0} Age:{1}", myAnonyClassObject.Name, myAnonyClassObject.Age};
We can also create other instances of the same anonymous class but with different values. For example:
var newMyAnonyClassObject = new {Name = "Deepak", Age = 23};
Read more: C# Corner