C# program to demonstrate method overloading based on types of arguments

Here, we are going to learn demonstrate method overloading based on types of arguments in C#.
Submitted by Nidhi, on November 09, 2020

Here, we will overload the Sum() method based on types of arguments.

Method Overloading: Method overloading is the type of static polymorphism; we can create multiple methods with the same name using method overloading.

Program:

The source code to demonstrate method overloading based on the type of arguments is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate method overloading 
//based on types of arguments

using System;

class MethodOver
{
    static double Sum(int a, int b)
    {
        float r = 0;

        r = a + b;
        return r;
    }
    static double Sum(int a, float b)
    {
        float r = 0;

        r = a + b;
        return r;
    }

    static double Sum(int a, double b)
    {
        double r = 0;

        r = a + b;
        return r;
    }
    static void Main(string[] args)
    {
        double result = 0;

        //Method with integer arguments
        result = Sum(10, 20);
        Console.WriteLine("Sum : " + result);

        //Method with integer and float arguments
        result = Sum(10, 20.24F);
        Console.WriteLine("Sum : " + result);

        //Method with integer and double arguments
        result = Sum(10, 27.38);
        Console.WriteLine("Sum : " + result);
    }
}

Output:

Sum : 30
Sum : 30.2399997711182
Sum : 37.38
Press any key to continue . . .

Explanation:

In the above program, we created a class MethodOver, here we overloaded the sum() method based on the type of arguments to calculate the sum of given arguments.

Here, we created the three methods to calculate the sum of given arguments and return the result to the calling method.

Now look to the Main() method. Here we created the local variable result and then called each overloaded method one by one and printed the result on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.