Click here to Skip to main content
15,878,959 members
Articles / Programming Languages / C#
Tip/Trick

Anonymous types

Rate me:
Please Sign up or sign in to vote.
4.62/5 (12 votes)
6 Dec 2010CPOL1 min read 68.6K   11   2
Anonymous types
What are Anonymous types ?

Anonymous types are the new concept in C#3.0 which allow to create new types without defining them.

Why are Anonymous types introduced in C#?

Anonymous types have been introduced to support one of the most useful features called LINQ. It's most useful when you are querying collection of object using LINQ query and you want to return only a few of its properties.

How to define Anonymous types ?

One can define Anonymous types easily by using new keyword of C#. Here is the example of it:

var pranay = new { id=1, Name= "pranay rana" };
var krunal = new { id=1, Name= "krunal mevada" };


LINQ query example


Querying the object collection having property Id, Name and Age but you just want to get only Id and Name after querying data, then code is like:

var user = from user in Users
                select new { user.Name, user.Id}


Here as you see select new i.e second line of code generates anonymous type.

Consider the below code to understand Anonymous type in more detail.
To define array of Anonymous type:

var persons = new[] { 
               new { id=1, Name= "pranay rana" },
               new { id=2, Name= "krunal mevada" },
               new { id=3, Name= "hemang vyas" } 
             };

          foreach (var person in persons)
            {
                Console.WriteLine("Person : " + person.id);
                Console.WriteLine("Person : " + person.Name);
            }


After compiling code, when you see your DLL or EXE file in ILDASM, it shows code generated by the compiler.




Line of code defines the Anonymous type which is generated by compiler
locals init ([0] class '<>f__AnonymousType0`2'<int32,string>[] persons,
           [1] class '<>f__AnonymousType0`2'<int32,string> person,
           [2] class '<>f__AnonymousType0`2'<int32,string>[] CS$0$0000,
           [3] class '<>f__AnonymousType0`2'<int32,string>[] CS$6$0001,
           [4] int32 CS$7$0002,
           [5] bool CS$4$0003)


Array of the type is defined as:

IL_0000:  nop
  IL_0001:  ldc.i4.3
  IL_0002:  newarr     class '<>f__AnonymousType0`2'<int32,string>


Create instance of Anonymous type:

IL_0015:  stelem.ref
  IL_0016:  ldloc.2
  IL_0017:  ldc.i4.1
  IL_0018:  ldc.i4.2
  IL_0019:  ldstr      "krunal mevada"
  IL_001e:  newobj     instance void class '<>f__AnonymousType0`2'<int32,string>::.ctor(!0,
                                                                                        !1)


Whole source code:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       136 (0x88)
  .maxstack  5
  .locals init ([0] class '<>f__AnonymousType0`2'<int32,string>[] persons,
           [1] class '<>f__AnonymousType0`2'<int32,string> person,
           [2] class '<>f__AnonymousType0`2'<int32,string>[] CS$0$0000,
           [3] class '<>f__AnonymousType0`2'<int32,string>[] CS$6$0001,
           [4] int32 CS$7$0002,
           [5] bool CS$4$0003)
  IL_0000:  nop
  IL_0001:  ldc.i4.3
  IL_0002:  newarr     class '<>f__AnonymousType0`2'<int32,string>
  IL_0007:  stloc.2
  IL_0008:  ldloc.2
  IL_0009:  ldc.i4.0
  IL_000a:  ldc.i4.1
  IL_000b:  ldstr      "pranay rana"
  IL_0010:  newobj     instance void class '<>f__AnonymousType0`2'<int32,string>::.ctor(!0,
                                                                                        !1)
  IL_0015:  stelem.ref
  IL_0016:  ldloc.2
  IL_0017:  ldc.i4.1
  IL_0018:  ldc.i4.2
  IL_0019:  ldstr      "krunal mevada"
  IL_001e:  newobj     instance void class '<>f__AnonymousType0`2'<int32,string>::.ctor(!0,
                                                                                        !1)
  IL_0023:  stelem.ref
  IL_0024:  ldloc.2
  IL_0025:  ldc.i4.2
  IL_0026:  ldc.i4.3
  IL_0027:  ldstr      "hemang vyas"
  IL_002c:  newobj     instance void class '<>f__AnonymousType0`2'<int32,string>::.ctor(!0,
                                                                                        !1)
  IL_0031:  stelem.ref
  IL_0032:  ldloc.2
  IL_0033:  stloc.0
  IL_0034:  nop
  IL_0035:  ldloc.0
  IL_0036:  stloc.3
  IL_0037:  ldc.i4.0
  IL_0038:  stloc.s    CS$7$0002
  IL_003a:  br.s       IL_007a
  IL_003c:  ldloc.3
  IL_003d:  ldloc.s    CS$7$0002
  IL_003f:  ldelem.ref
  IL_0040:  stloc.1
  IL_0041:  nop
  IL_0042:  ldstr      "Person : "
  IL_0047:  ldloc.1
  IL_0048:  callvirt   instance !0 class '<>f__AnonymousType0`2'<int32,string>::get_id()
  IL_004d:  box        [mscorlib]System.Int32
  IL_0052:  call       string [mscorlib]System.String::Concat(object,
                                                              object)
  IL_0057:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_005c:  nop
  IL_005d:  ldstr      "Person : "
  IL_0062:  ldloc.1
  IL_0063:  callvirt   instance !1 class '<>f__AnonymousType0`2'<int32,string>::get_Name()
  IL_0068:  call       string [mscorlib]System.String::Concat(string,
                                                              string)
  IL_006d:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0072:  nop
  IL_0073:  nop
  IL_0074:  ldloc.s    CS$7$0002
  IL_0076:  ldc.i4.1
  IL_0077:  add
  IL_0078:  stloc.s    CS$7$0002
  IL_007a:  ldloc.s    CS$7$0002
  IL_007c:  ldloc.3
  IL_007d:  ldlen
  IL_007e:  conv.i4
  IL_007f:  clt
  IL_0081:  stloc.s    CS$4$0003
  IL_0083:  ldloc.s    CS$4$0003
  IL_0085:  brtrue.s   IL_003c
  IL_0087:  ret
} // end of method Program::Main


Quick facts about Anonymous type

  • Anonymous types are reference types derived form system.objects.
  • Properties of the Anonymous type are read only.
  • If two Anonymous types have the same properties and same order, then the compiler treats it as the same type, but if both are in one assembly.
  • Anonymous type has method scope. If you want to return Anonymous type from the method, then you have to convert it in object type. But is not good practice.


Find more at : http://pranayamr.blogspot.com/

License

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


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
QuestionProperties of the Anonymous type are read only? Pin
_Dhull 19-Jan-15 19:34
_Dhull 19-Jan-15 19:34 
GeneralGood Tip Pin
Abdul Quader Mamun16-Dec-10 9:31
Abdul Quader Mamun16-Dec-10 9:31 

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.