Site icon

Anonymous Types in C#

C# allows you to declare a type or method without explicitly stating any name for it, which is known as the anonymous type. This is a powerful feature introduced in C# 3.0, it allows us to declare anonymous types inside a method without explicitly specifying their type information. If you haven’t gone through my previous article on implicitly typed local variable (Var), then you can do it here.

How to declare an Anonymous types in C#?

We can declare an anonymous type by using implicitly typed local variable pattern using var keyword. for example, in below, we define a class, having three properties ( FirstName , LastName of type String and Age of type Int32 ) and initializing their values.

Here we haven’t mentioned any explicit type after the new keyword. The compiler creates an anonymous type name automatically, which is unknown to us (that’s why its anonymous type).

So, here the C# compiler inferred the anonymous type and generated strongly typed properties. It created System.String type property for FirstName , LastName and   System.Int32 type property for Age.

What C# compiler does when it sees a Anonymous types in C#?

Let’s look into more detail and figure out what the C# compiler does when it finds an anonymous type.

For above code example, the compiler creates below line of IL (Intermediate Language) code.

If you look at it closely then, here the compiler creates

Below assembly dissembler code image can give a clear picture of the IL code.

Nested Anonymous types in C#:

If an anonymous type is present inside another anonymous type, then its called as nested anonymous type. Lets take below example.

If you debug and check the anonymous type in the quick watch, then you will see something similar to below.

As seen in the above image, the compiler creates Address an anonymous type inside student anonymous type and also creates the strongly typed properties based on their assignments.

Key Points:

Output to above:

Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on Dynamic type in C# , Nullable type in C# , Var type in C# and Reference Type and Value type .

Exit mobile version