Constructors overloading in c#

In this chapter you will learn:
  • What is constructor overloading?
  • How to use constructor overloading in C# program?

What is Constructor Overloading?

Constructor Overloading is a technique to create multiple constructors with a different set of parameters and the different number of parameters. It allows us to use a class in a different manner. The same class may behave different type based on constructors overloading. With one object initialization, it may show simple string message whereas, in the second initialization of the object with the different parameter, it may process an arithmetic calculation.

 

Programming Example of Constructors Overloading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Constructor_Overloading
{
    class GameScore
    {
        string user;
        int age;
        //Default Constructor
        public GameScore()
        {
            user = "Steven";
            age = 28;
            Console.WriteLine("Previous User {0} and he was {1} year old", user, age);
        }

        //Parameterized Constructor
        public GameScore(string name, int age1)
        {
            user = name;
            age = age1;
            Console.WriteLine("Current User {0} and he is {1} year old", user, age);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            GameScore gs = new GameScore(); //Default Constructor Called
            GameScore gs1 = new GameScore("Clark", 35); //Overloaded Constructor.
            Console.ReadLine();
        }
    }
}

Output

Previous User Steven and he was 28 year old
Current User Clark and he is 35 year old
__

Explanation

Constructor Creating:

In this example we have create two constructors. One is default constructor which modifies the variable string user, int age with their value. Very next we have created another constructor with different set of parameter which overloaded previous variable value with its own parameterized value.

string user;
int age;
//Default Constructor
public GameScore()
{
    user = "Steven";
    age = 28;
    Console.WriteLine("Previous User {0} and he was {1} year old", user, age);
}

//Parameterized Constructor
public GameScore(string name, int age1)
{
    user = name;
    age = age1;
    Console.WriteLine("Current User {0} and he is {1} year old", user, age);
}

Summary

In this chapter you have learned what the constructor overloading is and how to use in program. You have also seen the benefit of using constructor overloading in program. In the next chapter, we will see some more programming example of constructors and destructors which will enhance your understanding of object initialization with constructors.

More Articles

 

Share your thought