CSharp - Use Method Overloading to create Add() Method

Introduction

In the following code all the methods have the same name "Add".

But each method is doing different things.

This kind of code is called method overloading.

In method overloading, method names are the same but the method signatures are different.

What is a method signature?

Method name and its the number and types of parameters are method signature.

C# compiler can distinguish among methods with same name but different parameter lists.

For example, for C#, double Add(double x, double y) is different from int Add(int x, int y).

Demo

using System;

class MyClass//from   w  w  w.  java 2s . co  m
{
    public int Add(int x, int y)
    {
        return x + y;
    }
    public double Add(double x, double y)
    {
        return x + y;
    }
    public string Add(String s1, String s2)
    {
        return string.Concat(s1, s2);
    }
}
class Program
{
    static void Main(string[] args)
    {
        MyClass ob = new MyClass();
        Console.WriteLine("2+3={0}", ob.Add(2, 3));
        Console.WriteLine("20.5+30.7={0}", ob.Add(20.5, 30.7));
        Console.WriteLine("A + Bose ={0}", ob.Add("A", "B"));

    }
}

Result

Related Topic