Create and initialize objects and collections in one step in C# 3.0

Imagine you have the following class:

public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string City { get; set; }
}

Traditionally, when you need to create Customer objects and add them to a collection, you would do it like:

List<Customer> customers = new List<Customer>();
Customer customer1 = new Customer();
customer1.FirstName = "Homer";
customer1.LastName = "Simpson";
customer1.Street = "Evergreen terrace";
customer1.City = "Springfield";
customers.Add(customer1);
Customer customer2 = new Customer();
customer2.FirstName = "Marge";
customer2.LastName = "Simpson";
customer2.Street = "Evergreen terrace";
customer2.City = "Springfield";
customers.Add(customer2);

Obviously, this is a lot of work. Fortunately, in C# 3.0 there’s a way to create and initialize objects and collections in one step, using the object initializers feature: 

List<Customer> customers2 = new List<Customer>()
{
new Customer() { FirstName = "Homer", LastName = "Simpson",
Street = "Evergreen terrace", City = "Springfield" },
new Customer() { FirstName = "Marge", LastName = "Simpson",
Street = "Evergreen terrace", City = "Springfield" }
};

Much cleaner, isn’t it?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s