Topic : Constructor Overloading in C# Programming language:

Constructor Overloading:

Constructor is a special method of a Class which will Invoke Automatically Whenever Object of Class is created. Constructors are Responsible for Object Initialization and Memory Allocation of its class. If We create any Class Without Constructor, The Compiler Will Automatically Create One Default Constructor for that class. The Default Constructor Initializes all Numeric Fields in the class to Zero and All String and Object Fields to Null.





In Our Previous Tutorials (Overloading) , we already discuss about Overloading. in this tutorial, we will discuss about Constructor Overloading.

Constructor Overloading is a Technique to create multiple constructors with different arguments. It allows us to use a Single class in Many different ways. A same class may behave different type based on constructors overloading. Let's have a example to know, how exactly we can overload constructor, and why we need it.



/*Example - Constructor Overloading - InfoBrother*/

using System;

namespace ConstructorOverloading
{
    class Overload
    {
        string name;
        int temp;

        public Overload()  //Default Constructor:
        {
            name = "Abbottabad";
            temp = 29;
            Console.WriteLine("{0} Yesterday Temperature : {1}°.", name, temp);
        }

        //Parameterized Constructor: Overloading-
        public Overload(string nam, int tem)
        {
            name = nam;
            temp = tem;
            Console.WriteLine("{0} Today Temperature  : {1}°.", name, temp);
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Overload load = new Overload(); //Calling Default constructor:

            //calling Overload Constructor.
            Overload load2 = new Overload("Abbottabad", 26); 

            Console.ReadKey();
        }
    }
}


In Above example, we have created two constructors. one is default constructor and other is Parameterized Constructor Which Overloaded previous constructor.

Creating an Overloaded constructor is a simple as adding Overloaded Methods. The additional constructors are simply added to the code. Each constructor must have a Different arguments list.



















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement