lamda expression and anonymous types

Posted by Plhkrishna under ASP.NET category on | Points: 40 | Views : 948
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

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type, Cat. Note the use of auto-implemented properties in the Cat class. For more information, see Auto-Implemented Properties (C# Programming Guide).

class Cat
// Auto-implemented properties.
public int Age { get; set; }
public string Name { get; set; }


Cat cat = new Cat { Age = 10, Name = "Fluffy" };

Object Initializers with anonymous types

Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized by using an object initializer, as shown in the following declaration.

var pet = new { Age = 10, Name = "Fluffy" };

Comments or Responses

Login to post response