Pranay Rana: Anonymous types

Wednesday, December 1, 2010

Anonymous types

What is Anonymous types ?

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

Why Anonymous types introduced in C#?

Anonymous types introduce to support one of the most use full feature called LINQ. It's most use full when you are querying collection of object using LINQ query and you want to return only few property of it.

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 than 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 generate anonymous type.

Consider 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's shows code generated by compiler.



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

Array of the type is define is
IL_0000:  nop
  IL_0001:  ldc.i4.3
  IL_0002:  newarr     class '<>f__AnonymousType0`2'


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'::.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'[] persons,
           [1] class '<>f__AnonymousType0`2' person,
           [2] class '<>f__AnonymousType0`2'[] CS$0$0000,
           [3] class '<>f__AnonymousType0`2'[] 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'
  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'::.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'::.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'::.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'::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'::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 type derived form system.objects.
  • Properties of the Anonymous type is read only.
  • If two Anonymous type has same properties and same order than compiler treats its as same type. But if both are in one assembly.
  • Anonymous type has mehtod scope. If you want to return Anonymous type form the method than you have to convert it in object type. But is not good practice.

No comments:

Post a Comment