SiteMap  | About    

Anonymous Types In C#

Anonymous types are a feature of C# 3.0 , that allows data types to encapsulate a set of 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 each property is inferred by the compiler. C# allows you to create an object with the new keyword without defining its class.


Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. These are handy when you create types for "use and throw" purposes. You would not need to declare a class or a struct for every time you need a temporary type.

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. LINQ queries use them a lot, for example:

The { stud.Name, stud.Age } is an anonymous type that has a read-only Name and Age property. If you would iterate through the results of that query you could use that type as any other class:

In other words, you didn't have to define a new class that would look something like this:

The most popular use of anonymous types are for specifying projections in a LINQ to SQL query.

For example, the query

will be converted to this SQL:

With anonymous types , you can create ad hoc projections without defining the type for it beforehand. The compiler will define the type for you.

It is important to note that the scope of an anonymous type is local to the method where it is defined. You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. Moreover, Anonymous type is a reference type and all the properties are read-only. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type. (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.