Friday, May 7, 2021

C# Anonymous Type

Anonymous Type: It is a type without a name or identifier.

Important facts:
  1. It contains public read-only properties as its members.
  2. Fields, methods and events are not its members.
  3. The new operator is used to create its instance i.e. anonymous object, which is followed by curly braces. Its members i.e. properties are initialized inside curly braces.
  4. The properties cannot be initialized with null.
  5. The syntax of initialization of anonymous object is based on Object Initializer.
For example,
var student = new {Id =1, Name="Ajeet", Age= 27, Gender ='M', Scores =80 };

Anonymous type is always local to the method where it is defined. It means that anonymous type is short-lived. Obviously, it should not be used to pass the anonymous type instance from the method in which it is defined to another method.

In LINQ, with query expression, range variable can be used inside the body { } of anonymous object to select specific properties of the range variable.

As the anonymous object type is not explicit and cannot be explicitly expressed as per definition, its implicit type is System.Object class. We can verify it as follows:

var student = new {Id =1, Name="Ajeet", Age= 27, Gender ='M', Scores =80 };
Console.WriteLine(student.GetType().ToString());

The related concept is that of Anonymous Method.

No comments:

Post a Comment

Hot Topics