Thursday, January 8, 2009

C# 3.0 Object Initialization Expressions and Anonymous Types

Part 1:

We know for standard object initializer, we have class Customer

public class Customer {
public int Age;
public string Name;
public string Country;
public Customer(string name, int age){
this.Name=name;
this.Age=age;
}
}
we know the above code has defult constructor Customer(){} and none default constructor: Customer(string name, int age){this.Name=name;this.Age=age;}

The standard syntax is:
Customer c1=new Customer();
Customer c2=new Customer("Jack",28);

If we want to set Country but not Age, we need to write the code following:

Customer customer=new Customer();
customer.Name="Mike";
customer.Country="France";

C# 3.0 introduces a shorter form of object initiallizaion syntax:
Customer customer=new Cusomer{Name="Mike",Coutry="France"};

For default constructor,we can aslo have the following syntax:
Customer c3=new Customer(){Name="Mike",Coutry="France"};
nondefault constructor:
Customer c4=new Customer("Paolo",21){Country="Italy"};
The c4 assignment above is equivalent to:
Customer c4=new Customer("Paolo",21);
c4.country="Italy";

******************
Part 2:
C# 3.0 Can have anonymous types:
var c5=new {Name="Mike",Coutry="France"};
This code generates a class under the scenes (you never see it), that looks like as below:
class __Anonymous1
{
public string Name;
public string Country;
}

__Anonymous1 c5=new __Anonymous1()
c5.Name="Mike";
c5.Country="France";

No comments: