Search This Blog

Monday, July 8, 2019

Different Types Of Constructor In C#

A   consructor is a method used to initialize the state of  an object and  get invoked at the time of an object creation

  • Constructor name should be same as the class name
  • A  constructor  must have no return type even void 
  • static constructor can not be parametrized constructor
  • with in a class you can create one static  constructor
 Type of Construtor
  1.    Default Constructor 
  2.    Parametrized  Constructor 
  3.    Static Constructor 
  4.    Copy Constructor 
  5.    Private constructor

Copy Constructor  // c# does not suport copy constructor


namespace ConsoleApplication4
{
    class ExampleCopyConstructor
    {
        private string  aName;
        private int aAge;

      //  parametrized constructor
        public ExampleCopyConstructor(string aName, int aAge)
        {
            this.aName = aName;
            this.aAge = aAge;
        }
        // copy constructor 
        public ExampleCopyConstructor(ExampleCopyConstructor lobj)
        {
            aName = lobj.aName;
            aAge = lobj.aAge;
        }

        public string Data
        {

            get
            {
                return "The name of person is: " + aName +
                       " and age : " +
                                        aAge.ToString();
            }
        }


    }
    class Program
    {
        static void Main(string[] args)
        {
            ExampleCopyConstructor t1 = new ExampleCopyConstructor("Syam", 38);
            ExampleCopyConstructor t2 = new ExampleCopyConstructor(t1);
            Console.WriteLine(t2.Data);
            Console.ReadKey();
       
        }
    }

No comments :