Monday, July 13, 2009

collection Initializers in .Net 3.0

.Net offers a new features of initializing objects.

class people
{
public string FirstName { get; set; }
public string LastName { get; set; }
}



class main
{
static void Main()
{
//Method 1:Adding people to List
people People = new people();
List Names = new List();
People.FirstName = "Anish";
People.LastName = "Varghese";
Names.Add(People);
People.FirstName = "ani";
People.LastName = "marokey";
Names.Add(People);

//Method 2:Adding people to List
List Names1 = new List();
Names1.Add(new people { FirstName = "Anish", LastName = "Varghese" });
Names1.Add(new people { FirstName = "ani", LastName = "marokey" });

//Method 3:Adding people to List
List Names2 = new List()
{
new people{FirstName="Anish",LastName="Varghese"},
new people{FirstName="ani",LastName="marokey"}
};
//Method 4 :Adding people to List

List Names3 = new List { new people { FirstName = "Anish", LastName = "Varghese" }, new people { FirstName = "ani", LastName = "marokey" } };
}

Note :where we can use is a class has no default constructor and initialization is required.



0 comments:

 
Counter