What is anonymous type ?

Anonymous types serve as valuable tools for temporarily encapsulating information within the local scope. Introduced in C# 3.0, this innovative concept enables the creation of new types without explicitly defining them. These dynamically generated types are commonly employed to yield results within LINQ statements. It is important to note that anonymous types are reference types derived from System.Object, and their properties are read-only, ensuring immutability and safeguarding the integrity of the encapsulated data.

Anonymous types

One can define Anonymous types easily by using new keyword of C#.

var vr = new { Name = "Jack", Age = 22 };

Here the statement to verify that their inferred types are int and string.

Console.WriteLine(vr.Name + vr.Age);

Since anonymous types do not have a named typing, they must be stored in variables declared using the var keyword, telling the C# compiler to use type inference for the variable. In the following example, the names of the properties of the anonymous type are Name and Age.

var studentQuery = from stud in students select new { stud.Name, stud.Age }; foreach (var v in studentQuery) { Console.WriteLine("Name={0}, Age={1}", v.Name, v.Age); }
anonymous properties


Anonymous types offer a practical solution for efficiently returning multiple properties from a query without the need for explicit type declarations. When two anonymous types share the same properties in the same order, the compiler recognizes them as identical types, provided they are within the same assembly. This allows for seamless integration and enhanced type safety in scenarios where temporary or intermediate results are involved. By using anonymous types, developers can streamline their code and avoid unnecessary type definitions while maintaining a robust and concise programming approach.