Search

Mar 27, 2009

Anonymous Types in C# 3.0

We all know about Abstract Type, generally we are creating Class which are Abstract Type, A Class has name assigned with it. Anonymous Type are Class without specifying the name to it. You can create Anonymous class by using new operator. Consider the following example.

class AnonymousType
{
public string Name { get; set; }
public int Age { get; set; }
public string Country { get; set; }
}
.
.
.
AnonymousType a1 = new AnonymousType { Name = "Marco" };
var a2 = new AnonymousType { Name = "Paolo" };
var a3 = new { Name = "Tom", Age = 31 };
var a4 = new { a2.Name, a2.Age };
var a5 = new { a1.Name, a1.Country };
var a6 = new { a1.Country, a1.Name };



The variables a1 and a2 are of the AnonymousType, but the type of variables a3, a4, a5, and a6 cannot be inferred type, see more on Local Type Inference. The var keyword get the type based on assigned expression which must with new keyword and without a type specified.



The variables a3 and a4 are of the same anonymous type because they have the same fields and properties. Even if a5 and a6 have the same properties (type and name), they are in a different order, and that is enough for the compiler to create two different anonymous types.



You can use anonymous type in array initializer too, lets see and example.




var ints = new[] { 1, 2, 3, 4 };
var arr1 = new[] {
new AnonymousType { Name = "Marco", Country = "Italy" },
new AnonymousType { Name = "Tom", Country = "USA" },
new AnonymousType { Name = "Paolo", Country = "Italy" }};
var arr2 = new[] {
new { Name = "Marco", Sports = new[] { "Tennis", "Spinning"} },
new { Name = "Tom", Sports = new[] { "Rugby", "Squash", "Baseball" } },
new { Name = "Paolo", Sports = new[] { "Skateboard", "Windsurf" } }};



While ints is an array of int and arr1 is an array of AnonymousType, arr2 is an array of anonymous types, each containing a string (Name) and an array of strings (Sports). You do not see a type in the arr2 definition because all types are inferred from the initialization expression. Once again, note that the arr2 assignment is a single expression, which could be embedded in another one.



You can read more features from my older post, Automatic Properties, and Object-Collection Initialization, Local Type Inference and Partial Methods.

No comments: