Wednesday, September 5, 2007

Object Initializers in C# 3.0

C# 3.0 includes a new language feature called object initializers.

Object initializers enable you to initialize the state of an object with a single expression that does not require use of parameterized constructors.

Basically, this feature allows you to initialize an object by both creating the object instance (i.e. a new expression) as well as assign values to one or more properties in a single sentence, or to initialize a collection with a set of values to add to it in a single expression.

    class Program
static void Main(string[] args)
Customer cus1 = new Customer() { Name = "Maor", City = "Herzliya" };
Customer cus2 = new Customer() { Name = "Guy", City = "Ramat Hasharon" };

List<Customer> customers = new List<Customer>() { cus1, cus2 };


class Customer
public string Name { get; set; }
public string City { get; set; }


The first & the second lines initialize a Customer object with the default constructor (though you could call a constructor with parameters here), and assigns explicit values to the Name and City properties.

The third line initializes a collection of type List<Customer> with the objects cus1 and cus2. Tags:

Technorati Tags:

No comments: