C# Advance

C# Anonymous Type

C# anonymous type is a class with no name, meaning nameless class. Behind the scenes, C# compiler automatically generates its own unique type name with a class definition at compile time based on the properties provided in the curly braces ({ }). This simple type is declared on the fly to hold temporary data within the scope of a method, rather than explicitly define a full class definition. All the properties listed in the object initializer of an anonymous type are public and read-only.

When you define an anonymous type, you use new keyword followed by a pair of braces, specifying the names and the values of the public properties the type will contain. Most importantly, you need to use implicitly typed local variable with the var keyword to hold the reference of anonymous type, because the type’s name is invisible to user, generated by the compiler internally. The keyword var tells the compiler to infer the type of the variable automatically from the expression on the right side, after the equal (=) sign.

Here is an example of creating an anonymous type in C#. The declaration will create an object of an unnamed class with three read-only properties inferred from the anonymous object initializer: Name, Age, and IsMarried. The compiler determines the types of the properties from the types of the data you use to initialize them.

var temporary = new { Name = "Pirzada", Age = 35, IsMarried = true };

Now, you can access the properties in the object by using dot notation, like this:

Console.WriteLine($"Name = {temporary.Name}"); 
Console.WriteLine($"Age = {temporary.Age}"); 
Console.WriteLine($"Married = {temporary.IsMarried}");

Run Demo

OUTPUT

Name = Pirzada
Age = 35
Married = True

Anonymous Type in Short

  • Anonymous Type is a class type
  • Anonymous Type is a nameless class
  • Anonymous Type cannot define any methods
  • Anonymous Type only contain public and read-only properties
  • Anonymous Type properties must be initialized with a value, which cannot be null
  • Anonymous Type cannot be used as a parameter type on a method or as a return value
  • Anonymous Type provides ToString, Equals, and GetHashCode methods
  • Anonymous Type is mostly used in the select clause of a query expression to return properties

C# Reference | Microsoft Docs