Q:

C# program to demonstrate the constructor overloading

0

C# program to demonstrate the constructor overloading

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

The source code to demonstrate the constructor overloading is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate constructor overloading.

using System;

class CtorOver
{
    public CtorOver(int a, int b)
    {
        int result = 0;

        result = a + b;
        Console.WriteLine("Sum is: " + result);
    }

    public CtorOver(int a, int b, int c)
    {
        int result = 0;

        result = a + b + c;
        Console.WriteLine("Sum is: " + result);
    }

    public CtorOver(int a, int b, int c, int d)
    {
        int result = 0;

        result = a + b+c+d;
        Console.WriteLine("Sum is: " + result);
    }
    static void Main(string[] args)
    {
        CtorOver C1 = new CtorOver(10, 20);
        CtorOver C2 = new CtorOver(10, 20,30);
        CtorOver C3 = new CtorOver(10, 20,30,40);
    }
}

Output:

Sum is: 30
Sum is: 60
Sum is: 100
Press any key to continue . . .

Explanation:

In the above program, we created a class CtorOver, here, we overloaded the constructor based on the number of arguments to calculate the sum of given arguments.

public CtorOver(int a, int b)
public CtorOver(int a, int b, int c)
public CtorOver(int a, int b, int c, int d)

Now look to the Main() method. Here, we created the three objects C1C2, and C3. Then called each overloaded constructor one by one and printed the result on the console screen.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to demonstrate the index overloading... >>
<< C# program to demonstrate method overloading based...