Friday, 6 June 2008

.Net 3.5 -- C# 3.0 -- Anonymuous Types




The anonymous type has a type name but it is the compiler who generates the name, not the developer itself and you won’t see it in your code.
Anonymous types provide a way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler.
The following code snippet illustrates that, an anonymous type being initialized with two properties named Code and Name.

C#
var evals = new {code="100" ,Name = "Mark"}

VB.NET
Dim evals = New With {code="100" ,Name = "Mark"}

Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).
Anonymous types are created by using the new operator with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide).
Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed.
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 to a property that is being initialized with an expression.
C# 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);

}
శశిధర్

No comments: