Jul 29 2007

Anonymous Types

Category: C# 3.0Bil@l @ 13:42

Anonymous types is a new feature of C# 3.0. It allows developers to creat local objects without the need to have a real signature of a class. This is helpful sometimes, when you have methods that take as input a large number of input parameters. What you can do is simply create a new anonymous type and use it through out the local body of the method. This way, you will be dealing with a strongly type class containing all input parameters instead of dealing with seperate fields.

 1.
 Anonymous types allows grouping data into a class that is created
 automatically at compile-time.

 2.
 var x= new {a=1, b=2, c="Bilal"};
 
 The above statement is compiled and the following is created:
 class __Anonymous1
 {
  private int _a= 3;
  private int _b= 5;
  private int _c= "some text";

  public int a { get{ return _a; } set{ _a = value;} };
  public int b { get{ return _b; } set{ _b = value;} };
  public int c { get{ return _c; } set{ _c = value;} };
 }

 3.
 When we define a subset of a class as an anonymous type,
 we declare the anonymous type without the need to specify
 properties names, this is called Projection Initializer.

Hope this helps,
Regards

Tags:

Comments are closed