Sunday, September 28, 2014

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

i.e. We cannot update value of anonymously typed object. We can use it only for Read-only purpose.

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.

Anonymous 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. 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.
var customerQuery = from cust in customers
                    select new { cust.Name, cust.OrderAmount };

            foreach (var c in customerQuery)
                Console.WriteLine("Name={0}, Bill Amount={1}", c.Name, c.OrderAmount);

You must provide a name for a property that is being initialized with an expression.
var customer = new { Name = "Naren", Age = 27 };

Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.

If two or more anonymous object initializers in an assembly specify a sequence of properties that are in the same order and that have the same names and types, the compiler treats the objects as instances of the same type. They share the same compiler-generated type information.

No comments:

Post a Comment