Object & Collection Initializers :

Object Initializers: C # 3.0 new features which allow direct named initialization of public variables of a class with out need of constructors.This is a great feature as it removes the need to create multiple overloaded constructors using different parameter lists to achieve the same goal. While you can currently create your own constructors, Object initializers are nice because you do not have to create multiple overloaded constructors to handle the various combinations of how you might want to initialize the


class Student

    {

        public int RollNo;

        public string StuName;

        public float Total;

    }

  

    class Program

    {

        static void Main(string[] args)

        {

            Student s1 = new Student { RollNo = 21, StuName = “shalini

            p”, Total = 83.63 };

        }      

    }

 

Collection Initializers: Prior to C# 3.0, it’s not allowed to initialize the collection of objects during initialization itself, i.e. First need to initialize and then need to add objects to the collection variables.

But with this Collection Initialisers, we can initialize the list of objects as


 

    class Student

    {

        public int RollNo;

        public string StuName;

        public float Total;

    }

  

    class Program

    {

        static void Main(string[] args)

        {

            List<Student> sList = new List<Student> { new Student {

            RollNo = 1, StuName = “shalini”, Total = 83 }, new Student

            { RollNo = 2, StuName = “pratyusha”, Total = 82 } };

 

        }      

    }

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s