Wednesday 28 August 2013

What is Collection Initializer in c#.

Collection Initializer is used to create an instance of collection class and assign a value to any accessible fields or properties of it at the same time. It is not necessary to explicitly create a constructor.

Example:-

class Cat
{
    // Auto-implemented properties.
    public int Age { get; set; }
    public string Name { get; set; }
}

List<Cat> cats = new List<Cat>()
{
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 },
    new Cat(){ Name = "Sasha", Age=14 }
};

OR:-


List<int> MyInts = new List<int>() { 1, 2, 3, 5, 6, 7 };

No comments:

Post a Comment

Note: only a member of this blog may post a comment.