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

Imagine you have the following class:

  1: public class Customer
  2: {
  3:   public string FirstName { get; set; }
  4:   public string LastName { get; set; }
  5:   public string Street { get; set; }
  6:   public string City { get; set; }
  7: }

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

  1: List<Customer> customers = new List<Customer>();
  2: Customer customer1 = new Customer();
  3: customer1.FirstName = "Homer";
  4: customer1.LastName = "Simpson";
  5: customer1.Street = "Evergreen terrace";
  6: customer1.City = "Springfield";
  7: customers.Add(customer1);
  8: Customer customer2 = new Customer();
  9: customer2.FirstName = "Marge";
 10: customer2.LastName = "Simpson";
 11: customer2.Street = "Evergreen terrace";
 12: customer2.City = "Springfield";
 13: 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:

  1: List<Customer> customers2 = new List<Customer>()
  2: {
  3:   new Customer() { FirstName = "Homer", LastName = "Simpson",
  4:                    Street = "Evergreen terrace", City = "Springfield" },
  5:   new Customer() { FirstName = "Marge", LastName = "Simpson",
  6:                    Street = "Evergreen terrace", City = "Springfield" }
  7: };

Much cleaner, isn’t it?

May 6, 2010 05:15 by lustuyck
E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed