Saturday, July 17, 2010

Initialize properties in an object

For example, you have a class which looks like this:

class Customer
{
public string account_code { get; set; }
public string name { get; set; }
public string email { get; set; }
}
This is what we used to do to initialize the properties in a new object:

Customer c1 = new Customer();
c1.account_code = "a001";
c1.name = "ABC Ltd Co";
c1.email = "info@abc.testing.com";
Starts from C# 3.0, you may initialize the properties in a new object instance in a single line of code which looks like this:

Customer c2 = new Customer()
{ account_code = "a001",
name = "ABC Ltd Co",
email = "info@abc.testing.com" };

No comments:

Post a Comment