Sunday, 21 December 2014

Method Overloading in C#

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


In VB.net when you are overloading a method of the base class in derived class, then you must use the keyword “Overloads”.


But in C# no need to use any keyword while overloading a method either in same class or in derived class.


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


Example for Method Overloading


using System;

namespace ProgramCall
{

    class Class1
    {

        public int Sum(int A, int B)
        {
            return A + B;
        }

        public float Sum(int A, float B)
        {
            return A + B;
        }
    }

    class Class2 : Class1
    {
        public int Sum(int A, int B, int C)
        {
            return A + B + C;

        }
    }

    class MainClass
    {
        static void Main()
        {

            Class2 obj = new Class2();

            Console.WriteLine(obj.Sum(10, 20));

            Console.WriteLine(obj.Sum(10, 15.70f));

            Console.WriteLine(obj.Sum(10, 20, 30));

            Console.Read();
        }

    }
}

Output

30
25.7
60


Note

Method overloading provides more than one form for a method. Hence it is an example for polymorphism.


In case of method overloading, compiler identifies which overloaded method to execute based on number of arguments and their data types during compilation it self. Hence method overloading is an example for compile time polymorphism.

No comments:

Post a Comment