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.

Example
var student = new { Name= "John", Marks = 890, Passed = true }; Console.WriteLine(student.Name + student.Marks + student.Passed);

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:

var studentQuery = from stud in students select new { stud.Name, stud.Age };

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:

foreach (var st in studentQuery) { Console.WriteLine("Name={0}, Age={1}", st.Name, st.Age); }

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

public class studentClass { public Name {get;} public Age {get;} }

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

For example, the query

from x in db.MyTable select new {x.FirstColumn, MyAlias = x.SecondColumn }

will be converted to this SQL:

SELECT FirstColumn, SecondColumn AS MyAlias FROM MyTable

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.