Saturday, December 15, 2007

Object Initializers in C# 3.0

Hi

C# 3.0 introduced something called as object initializers.

Consider following class

class Person
{
public int Age;
public string Name;
.....
}

One can instantiate this class as

Person firstPerson = new Person();
firstPerson.Age =10;
firstPerson.Name = "Bal";

We can also use the parametrized constructors for initializing attributes of a class.

With C# 3.0 we can create the Person object as

Person secondPerson = new Person{ Age = 10, Name ="Bandu" };

This is not same as creating the object and setting its values.

The expression is evaluated right to left and hence a temporary object is created which is finally assigned to the secondPerson.

One good thing about this expression is this is an atomic expression.
Means we don't have to specify any lock kind of construct when using this in multi threaded programs.


Thanks

No comments: