Anonymous types - C#

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. 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.

You create anonymous types by using the new operator together with an object initializer

var v = new { Amount = 108, Message = "Hello" };  
  
// Rest the mouse pointer over v.Amount and v.Message in the following  
// statement to verify that their inferred types are int and string.  
Console.WriteLine(v.Amount + v.Message);  

 

Important Points:

  • It is derived from System.Object class and it is also a sealed class. So, the properties of anonymous type are read-only means you cannot change their values.
  • It also has intellisense support in Visual Studio.
  • It can contain one or more read-only properties.
  • It does not contain class members such as events, methods, etc.
  • The expression that used to initialize properties are not null, anonymous method, or a pointer type.
  • You can also create an anonymous type array.
  • It cannot be cast to any other type except an object.
  • It is of reference type.
  • You are not allowed to create a field, property, event, or return type of a method is of anonymous type.
  • You are not allowed to declare formal parameters of a method, property, constructor, indexer as a anonymous type.
  • The scope of the anonymous type is always limited to the method in which they are defined. Due to their local scope, you are not allowed to pass an anonymous type to another method, but you can pass it to those methods which can accept dynamic type parameters. As shown in the below example.

    Note: Generally, passing anonymous type using dynamic type is not recommended.