Object Initializer in c#


With Object Initializer , you can easily assign data to specific properties in a type , without explicitly creating constructors.

 The default constructor is invoked in the processing of object initializers.

Example Program for Object Initializer in c#


using System;

using System.Threading;

 

namespace ProgramCall

{

 

    class MainClass

    {

 

        public class Person

        {

            public string Name { get; set; }

            public int Age { get; set; }

        }

        static void Main(string[] args)

        {

 

            Person p1 = new Person { Name = "John", Age = 23 };

            //parentesis are optional

            Person p2 = new Person() { Name = "John", Age = 23 };

            Person p3 = new Person { Age = 45 };

 

            //will print output - John

            Console.WriteLine(p1.Name);

 

            Console.Read();

        }

    }

}

 




c# use object initializer, c# object initialization, c# object initializer, object initializer, object initializer in .net, object initializer in c#.net, object initializer in c#