C# : How to use object Initializers

4/1/2014

Object initializers is very helper at many case. For example, you can use at following case.

easy case
Product t = new Product{ id = 1, name = "code" };

It's able to use more complex case. If you created following two class.

sample class
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Desc { get; set; }
public Catgory Category { get; set; }
}
public enum Catgory
{
TV,
DESK,
IPOD,
IPHONE
}
complex case for object initializersList<Product> products = new List<Product>()
{
new Product { Id = 1, Name = "test", Desc = "test test"Category =Catgory.DESK } ,
 
new Product { Id = 2, Name = "test1", Desc= "testtestettt"Category =Catgory.IPHONE }
};