Introduction:

In this article we will explain to what is Method Overloading in c # or how to create a method in c# or how to use Method Overloading in c# or use different data type parameter with same method name in a class with example.

Description:

The process of creating more than one method with different signatures in a class with same name or creating a method in derived class with same name as a method with different signatures in base class is called as method overloading.

While methods overloading, a rule to follow is the overloaded methods must differ either in number of signature they take or the data type of at least one signatures.

Example for Method Overloading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Method_overloading
    {
        public int Addition(int a, int b)
        {
            int x;
            return x = a + b;
        }
        public int Addition(int a, int b, int c)
        {
            int y;
            return y = a + b + c;
        }
        public float Addition(float a, float b)
        {
            float u;
            return u = a + b;
        }
        public float Addition(float a, float b, float c)
        {
            float v;
            return v = a + b + c;
        }
    }
    class Program
    {
     static void Main(string[] args)
     {
      Method_overloading overload = new Method_overloading();
      Console.WriteLine("Addition of two integer type values:" + overload.Addition(2, 5));
      Console.WriteLine("Addition of two double type values:" + overload.Addition(1.25f, 2.23f));
      Console.WriteLine("Addition of three integer type values:" + overload.Addition(2,5, 5));
      Console.WriteLine("Addition of three double type values:" + overload.Addition(3.10f, 4.5f, 6.75f));
      Console.ReadLine();
    }
 
    }
}

 

Output

Addition of two integer type values: 7

Addition of two double type values: 48

Addition of three integer type values: 12

Addition of three double type values: 14.35

 

Note

Method overloading follow a rule to allow more than one method same name in a class. Hence it is an example for polymorphism.


I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like