Click here to Skip to main content
15,886,666 members
Articles / Programming Languages / MSIL
Tip/Trick

Compiler and Anonymous Type

Rate me:
Please Sign up or sign in to vote.
4.67/5 (7 votes)
18 Sep 2013CPOL1 min read 14.1K   3   2
How compiler manage anonymous types

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.

C#
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

  1. All properties are read only property.
  2. 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).
  3. 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.
  4. 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect ICRA Online Ltd.
India India
He has a experience of 10+ years in .Net Technology, he like to learn and share thinks about coding and development process.

Quora | LinkedIn | Twitter

Comments and Discussions

 
GeneralMy vote of 5 Pin
patel_pratik18-Sep-13 19:38
patel_pratik18-Sep-13 19:38 
GeneralRe: My vote of 5 Pin
Suvabrata Roy18-Sep-13 19:49
professionalSuvabrata Roy18-Sep-13 19:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.