Sunday, May 13, 2012

Anonymous Types

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 type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide).
The following example shows an anonymous type that is initialized with two properties named Amount and Message.
var v = new { Amount = 108, Message = "Hello" };

// Rest the mouse pointer over v.Amount and v.Message in the following
// statement to verify that their inferred types are int and string.
Console.WriteLine(v.Amount + v.Message);
Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.
'
nonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.
The most common scenario is to initialize an anonymous type with properties from another type. In the following example, assume that a class exists that is named Product. Class Product includes Color and Price properties, together with other properties that you are not interested in. Variable products is a collection of Product objects. The anonymous type declaration starts with the new keyword. The declaration initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query.
If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name for a property that is being initialized with an expression, as shown in the previous example. In the following example, the names of the properties of the anonymous type are Color and Price.
var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
    Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}

Typically, when you use an anonymous type to initialize a variable, you declare the variable as an implicitly typed local variable by using var. The type name cannot be specified in the variable declaration because only the compiler has access to the underlying name of the anonymous type. For more information about var, see Implicitly Typed Local Variables (C# Programming Guide).
You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example.
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};

compiler generates an internal sealed class that models the anonymous type. The anonymous type is immutable; all the properties are read only.  you cannot declare methods that take anonymous types as parameters, nor can you return them from methods

 if anonymous types are so limited, why use them at all? In my opinion, there are two related reasons. First, the compiler writes code faster than I do. The compiler creates a page full of code for each new anonymous type. That’s code I don’t have to write, test, and debug myself. It’s a great time saver. Second, anonymous types are great for local values that support algorithms, but aren’t part of the overall object model for a system. Because the types are anonymous, they don’t clutter the picture of the system as a whole. You don’t browse the code for an anonymous type. Anonymous types do not show up in Class View. Anonymous types don’t require external documentation. They just quickly provide a small bit of functionality. 


Anonymous types as the name suggests,  help us  to create an object without declaring its data type. Since name of the data type is not specified that the type is referred to as an anonymous type.
We have lot of resources around us on this concept, but I still see some confusion and arguments on this concept that made me to write this blog post. I will try to explain it in simple words so that a novice can understand the basics of the concept.
VB.NET
1.Emp = New With {
2.         .EmplD = 123,
3.         .FName = "Hima",
4.         .LName = “Vejella” ,
5.         .Country = "India"
6.            }
C#.NET
1.var Emp = new {
2.        FirstName = "Hima",
3.        LastName = "Vejella",
4.        DOJ = DateTime.Now,
5.        EMPCode = 150
6.          };
The above code snippet is an anonymous declaration in VB. We can notice that the as key word is not required to declare it.
Visual Studio Editor is user-friendly to give us the IntelliSense as below. Once you declared the type then you can access all the properties.
ananymoustypes
When the above code reaches the complier these are the steps that are done internally.
  1. Compiler automatically generates anonymous class.
  2. It anonymously instantiate an object that contains the properties in anonymous type
  3. The instantiated object is assigned to the anonymous type variable "Emp"
The anonymous type inherits from Object, it holds the properties specified in declaring the object.

No comments:

Post a Comment