CSharp - Overload constructor to accept different number of parameter

Introduction

You can write a similar program for constructor overloading.

Demo

using System;

class MyClass/*w  ww  .ja  v  a  2  s  .c o  m*/
{
    public MyClass()
    {
        Console.WriteLine("Constructor with no argument");
    }
    public MyClass(int a)
    {
        Console.WriteLine("Constructor with one integer argument {0}", a);
    }
    public MyClass(int a, double b)
    {
        Console.WriteLine("You have passed one integer argument {0} and one double argument {1} in the constructor", a, b);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass ob1 = new MyClass();
        MyClass ob2 = new MyClass(25);
        MyClass ob3 = new MyClass(10, 25.5);
        //MyClass ob4 = new MyClass(37.5);//Error
        Console.ReadKey();
    }
}

Result

Analysis

A constructor has the same name as a class and it has no return type.

You can consider a constructor as a special kind of method that has the same name as a class and no return type.

Related Topic