Better ways of initializing the object, collections and setting the values

SheoNarayan
Posted by SheoNarayan under C# category on | Points: 40 | Views : 6783
After .NET Framework 3.5 (that comes with C# 3.0), the object and collection initialization has become easier and compact.

For example, assume that I have a Person object like this
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
}



Before C# 3.0 , we used to initialize the object and set its properties something like
// Traditional way of initializing the object and setting the properties
Person p = new Person();
p.FirstName = "Sheo";
p.LastName = "Narayan";
p.City = "Hyderabad";


To initialize collection and add objects, we used to write something like this

// Traditional way of initialzing the collection and adding the object
IList<Person> list = new List<Person>();
// add first object
Person p1 = new Person();
p1.FirstName = "Sheo";
p1.LastName = "Narayan";
p1.City = "Hyderabad";
list.Add(p1);
// add second object
Person p2 = new Person();
p2.FirstName = "Sheo";
p2.LastName = "Narayan";
p2.City = "Hyderabad";
list.Add(p2);


From C# 3.0 onwards , we can now initialize the object and set its property something like

// New way of initializing the object and setting the properties
Person pp = new Person { FirstName = "Sheo", LastName = "Narayan", City = "Hyderabad" };


to initialize collection and add objects, we can do

// New way of initializing the collection
IList<Person> list1 = new List<Person>()
{
new Person { FirstName = "Sheo", LastName="Narayan", City="Hyderabad"},
new Person { FirstName = "Sam", LastName="Mark", City="New York" }
};

// adding new item to the collection
list.Add(new Person { FirstName = "Mark", LastName = "Hedge", City = "Chicago" });

Comments or Responses

Login to post response