C# Advanced

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 C# 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 an anonymous type, because the type’s name is invisible to the 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.


C# Anonymous Type Example

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


C# Anonymous Type in Short

  • Class type
  • Nameless class.
  • Cannot define any methods.
  • Only contain public and read-only properties
  • Properties must be initialized with a value, which cannot be null.
  • Cannot be used as a parameter type on a method or as a return value.
  • Provides ToString, Equals, and GetHashCode methods.
  • Mostly used in the select clause of a query expression to return properties.

C# Reference | Microsoft Docs