Friday 22 February 2013

Constructor Overloading

Just like we can overload the methods of a class in the same way we can also overload the constructors of a class i.e it is possible to define multiple constructors under a class changing their signatures.
    If a constructor of a class are overloaded we can create object of that class by making use of any constructor available or we can create a separate object by using a separate constructor.

Add a class LoadCon.cs and write the following code.

// Constructor Overloading

using System;
namespace CSharpConsole
{
    class LoadCon
    {
        int x;
        public LoadCon()     //default constructor
        {
            x = 10;
        }
        public LoadCon(int x)
        {
            this.x = x;

        }
        public void Display()
        {
            Console.WriteLine("The value of x is:{0}",+ x);
        }
        static  void Main()
        {
            LoadCon c1 = new LoadCon();
            LoadCon c2 = new LoadCon(20);
            c1.Display();
            c2.Display();
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment