When and why we use method overloading in c#?

Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task. 
You should consider overloading a method when you for some reason need a couple of methods that take different parameters, but conceptually do the same thing. 

Method overloading showing many forms.

 using System;
 
namespace method_overloading_polymorphism
{
    Class Program
    {
        Public class Shape
        {
            Public void Area (float r)
            {
                float a = (float)3.14 * r;
                // here we have used function overload with 1 parameter.
                Console.WriteLine ("Area of a circle: {0}",a);
            }
 
            Public void Area(float l, float b)
            {
                float x = (float)l* b;
                // here we have used function overload with 2 parameters.
                Console.WriteLine ("Area of a rectangle: {0}",x);
 
            }
 
            public void Area(float a, float b, float c)
            {
                float s = (float)(a*b*c)/2;
                // here we have used function overload with 3 parameters.
                Console.WriteLine ("Area of a circle: {0}", s);
            }
        }
 
        Static void Main (string[] args)
        {
            Shape ob = new Shape ();
            ob.Area(2.0f);
            ob.Area(20.0f,30.0f);
            ob.Area(2.0f,3.0f,4.0f);
            Console.ReadLine ();
        }
    }


Things to keep in mind while method overloading

  • If you use overload for method, there are couple of restrictions that the compiler imposes.
  • The rule is that overloads must be different in their signature, which means the name and the number and type of parameters
  • There is no limit to how many overload of a method you can have. You simply declare them in a class, just as if they were different methods that happened to have the same name.


Need Help? Contact Us.

Log in

*
*

Forgot password?

*

New User

*
*
*
*