What is the use of Anonymous types in C#

No.of Views2038
Bookmarked0 times
Downloads 
Votes0
By  pranay rana   On  25 Feb 2011 08:02:36
Tag : CSharp , CSharp4.0
Anonymous types are the new concept in C#3.0 which allow to create new types without defining it.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

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.

Image Loading

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)
</int32,string></int32,string></int32,string></int32,string>

Array of the type is define is

IL_0000:  nop
  IL_0001:  ldc.i4.3
  IL_0002:  newarr     class '<>f__AnonymousType0`2'<int32,string>
 
</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)
</int32,string>

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
 
</int32,string></int32,string></int32,string></int32,string></int32,string></int32,string></int32,string></int32,string></int32,string></int32,string>

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.
 
Sign Up to vote for this article
 
About Author
 
pranay rana
Occupation-CEO
Company-GMind Solusion
Member Type-Expert
Location-India
Joined date-08 Jan 2011
Home Page-http://pranayamr.blogspot.com
Blog Page-http://pranayamr.blogspot.com
Hey, I am Pranay Rana, working as a Senior Software engineer in mid-size company located in ahmedabad. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 4.3 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 me on my blog - http://pranayamr.blogspot.com/ StackOverFlow - http://stackoverflow.com/users/314488/pranay My CV :- http://careers.stackoverflow.com/pranayamr
 
 
Other popularSectionarticles
    In this article, i will explain how to use the How to use ExpandoObject Class in .NET 4.0.The ExpandoObject class is introduced on .NET Framework 4.0 and inherited using many interfaces.
    Published Date : 16/Apr/2011
    C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects
    Published Date : 26/May/2010
    Dynamic Datatype in C# 4.0 is quit bit familiar to Var Datatype. Deference between Var and Dynamic is VAR initialized on CompileTime and Dynamic initialized On Runtime
    Published Date : 17/May/2010
    In this article I will show how to use the IObserver and IObservable Interfaces in C#. These two interfaces is work with connection to Push based approach on Reactive Framework
    Published Date : 15/Dec/2010
    Through this article, i will introduce in FCL named Tuple which can store n - number of values in it. Yes, you specify the type of each of those variables as generic parameters, and the object will create those values for you
    Published Date : 15/Nov/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top