Introduction
In this tip, I will explain how anonymous types work with MSIL, and how the framework manages them and anonymous types.
What is an Anonymous Type?
Anonymous type means a user will define properties of a type and the compiler will create that type with a compiler generated name and the type details at compile time.
If you want some regular definition, then you can check it out on MSDN.
var AnoClass = new { Name = "Suvabrata", Age = 25,Sex='M' };
The above statement will create a class which has three properties and that class would be named at compile time like <>f__AnonymousType0`3
.
- Now why do compilers choose this name?
- How will the compiler create or build those types?
- What is the advantage of these types?
These classes are named in a pattern that starts with <>f__AnonoymousType
, now 0
is the index or sequence of that class and 3
is the property count of that class.
Features of Anonymous Class
- All properties are read only property.
- Compiler will create different classes for anonymous type depending on property name (Case sensitive), property sequence and property count. It does not depend on Property type (as they are generic types created by compiler).
- You cannot declare a field, a property, an event, return type of a method, formal parameter of a method, property, constructor, or indexer as having an anonymous type.
- Don't try to pass anonymous types outside of method boundary. If you pass anonymous type outside of method boundary, it will defeat the purpose of strong types.
Anonymous type is basically a generic type (as compiler creates) what the user will name each property the compiler will create a generic property at compile time by taking the right hand side's type.