Home > DeveloperSection > Blogs > Method Overloading and Overriding in C#

Method Overloading and Overriding in C#


C# C# 
Ratings:
0 Comment(s)
 2189  View(s)
Rate this:

Method Overloading and Overriding in C#

In this blog I am trying to explain the concept of method overloading and method overriding in C#.

Method overloading:  Method overloading is the process of creating multiple versions of existing method by overloading the parameter list (argument list) in the method signature.

in method  overloading the method  return  type and  method name  must be same, the  parameter list is  changed /overloaded. Usually method overloading is concerned within the same class unlike Method overriding. Thus we can have in single class multiple function of same name.

Need of method overloading, is only when we need common task but the parameter   is deferent in each operation, then method overloading is very helpful technology, where only one method interface but operate differently on the basis of parameter passed to the method.

Some time method overloading is also known as static binding or static polymorphism or early binding, where compiler know which method to be blinded to which object in advance.

Prototype  

<access specifier > <return type>methodNmae

(<argument type><argumentName>…… <argument type><argumentName..n>)

NOTE: in overloading the return type must be same in each version of method only argument list is overloaded.

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace methodoverloading

{

    class A

    {

        static void ain(String[] arg)

        {

             B addOperation=new B(5,8);

            int res;

            res=addOperation.sum();//calling method sum without any parameter

            Console.WriteLine("sum:{0}",res);

            res = addOperation.sum(10);// calling second version of overloaded method sum

            Console.WriteLine("sum:{0}", res);

          res = addOperation.sum(10, 20);//calling third version of overloaded method sum

            Console.WriteLine("sum:{0}", res);

     res = addOperation.sum(10, 20, 30);//calling fourth version of overloaded method sum

            Console.WriteLine("sum:{0}", res);

       res = addOperation.sum(4.0, 6.0);//calling fifth version of overloaded method sum

            Console.WriteLine("sum:{0}", res);

            Console.ReadKey();

        }

    }

    class B

    {

        protected int n1;

        protected int n2;

        public B()

        {

            this.n1=0;

            this.n2=0;

        }

        public B(int n,int m)

        {

            this.n1=n;

            this.n2=m;

        }

        public int sum(int n)

        {

            return(n1+n2+n);

        }

        public int sum()

        {

            return(n1+n2);

        }

        public int sum(int n,int m)

        {

            return(n+m);

        }

        public int sum(int n,int m,int p)

        {

            return(n+m+p);

        }

        public int sum(double n, double m)

        {

            return(Convert.ToInt32(n+m));

       }

    }

}

In above program the only method one method sum is created and overloaded four times in the class, within the deferent parameter list.

Method Overriding: is the process of creating new definition of existing method of Base class, in its derived class. The method overriding is concerned with inheritance where base class method is overridden in derived class as new functionality.

The overriding class (base class) must write the exactly same method signature while overriding the base class method. The overridden method must declare as virtual method in base class.

Need of method overriding in raised when we want new implementation of base class method while the method is same. The definition of base class method needs to be change. Let’s take an exclusive example suppose a manufacturing company have a cell phone of version 1.0, which have a common method call() ,which connects the called person and process the conversation . After few years latter company thinks about to enhancement in functionality of old version. So if he lunches’ a new version of that cell phone says version1.1, so it is obvious he did not remove main method “call ()” from new version1.1. Thus he must inherit the first version method “call ()” (i.e. version 1.0 work as base class (version) in next version1.1 (i.e version1.1 as derived class (version)) with new additional functionality to base version1.0, as now” call()” method :

·         show the call connect time,

·         call summary of

·         record when last time connect

·          Record call summary on each individual call. Etc

As we seen in the above case you have only one option of method overriding, instead of creating new method. Thus it is good example for understanding when to use method overriding.

 Prototype:

Overriding in c# is achieved using the Virtual keyword in base class’s method .which in turn the derived class override the virtual method of base class. In c# virtual methods are not compulsory to override, if you don’t interested to change the definition of old base class definition that however exist in base class. Thus the conclusion is that, in order to override the method of base class you must declare method as virtual method.

e.g

Public virtual overrideMe( string message);// base class method to be overridden.

Now let’s take and dummy example to illustrate the method overriding and method overloading technology in c# implementation:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace staticPolymorphism

{

    class Program

    {

        static void Main(string[] args)

        {

            mathOperation mo=new mathOperation();

            operation op = new operation();

            int res, res1;

            Console.Clear();

            res=op.add(5,200);// actual method called here

            Console.WriteLine(res);

            res=op.add(5,200,30);// overloaded add(a,b,c)method called here

            Console.WriteLine(res);

            res1 = mo.add(20,50);//overriden method called here          

           Console.WriteLine("sum ={0}",res1);

           res = op.add(6.0, 7.2);

           Console.WriteLine("result of overloded function:{0}", res);          

          

            Console.ReadKey();

        }

    }

    class mathOperation:operation

    {//  base class method sum() had overriden here.

        public override int add(int n1, int n2)

        {

            Console.WriteLine("the sum of number:{0}+{1}={2}", n1, n2, n1 + n2);

           

          return(n1+n2);

        }

        public void msg()

        {

            Console.WriteLine("good evening ");

        }

      //method sub() is overridden in deriver class”mathoperation”          

        public override int sub(int n1, int n2)

        {

            Console.WriteLine("the subtraction of number:{0}-{1}", n1, n2);

            return (n1 - n2);

        }

//method multi() is overridden in deriver class”mathoperation”          

        public override int multi(int n1, int n2)

        {

            Console.WriteLine("the multiplication of number:{0}*{1}", n1, n2);

            return (n1 * n2);

        }

//method divide() is overridden in deriver class”mathoperation”          

        public override int divide(int n1, int n2)

        {

            Console.WriteLine("the divide of number:{0}/{1}", n1, n2);

            return (n1 / n2);

        }

    }

    class operation         //base class “opration”

    {

        public int number1, number2;

        public operation(int n1 = 0, int n2 = 0)

        {

            this.number1 = n1;

            this.number2 = n2;

        }

//method add() overloaded multiple time with deferent paramerer         

        public virtual int add(int n1, int n2)

        {

            return(n1 + n2);

        }

//method add() overloaded

        public virtual int add(double n1, double n2)

        {

            return (Convert.ToInt32(n1 + n2));

        }

//method sub() overloaded

        public virtual int sub(int n1, int n2)

        {

            return (n1 - n2);

        }

//method add() overloaded

        public virtual int add(int n1, int n2, int n3, int n4)

        {

            return (n1 + n2 + n3 + n4);

        }

//method sub() overloaded  and all methods are overloaded in this class

        public virtual int sub(float n1, float n2)

        {

            return (int)(n1 - n2);

        }

        public virtual int multi(int n1, int n2)

        {

            return (n1 * n2);

        }

        public virtual int multi(float n1, float n2)

        {

            return (Convert.ToInt32(n1 * n2));

        }

        public virtual int multi(int n1, int n2, int n3, int n4)

        {

            return (n1 * n2 * n3 * n4);

        }

        public virtual int divide(int n1, int n2)

        {

            return (n1 / n2);

        }

        public virtual int divide(float n1, float n2)

        {

            return (Convert.ToInt32(n1 / n2));

        }

    }

}

The above class explain concept of method overloading and method overriding in c#. In base class the virtual keyword is used to indicate, that all these method could be overridden in base class. However it is optional, in case you have not needed to redefine the base class method, do nothing.

One  more useful concept to redefining base class method’s new definition by using new key word  at the place of override.

Public  new  int sum( int n1,. Int n2);

 This line causes new definition of add () method of base class is created in its derived class. We can hide the base class members (e.g instance variable, methods, properties, delegate, event etc.)

Example

class mathOperation:operation

    {

   //making new definition of add() method of base class as explaind=ed in previous class

        public new int add(int n1, int n2)

        {

            Console.WriteLine("the sum of number:{0}+{1}={2}", n1, n2, n1 + n2);

            //int res = n1 + n2;

          return(100);

        }

        public void msg()

        {

            Console.WriteLine(n1+"<=>"+n2);

        }

        public new int sub(int n1, int n2)

        {

            Console.WriteLine("the subtraction of number:{0}-{1}", n1, n2);

            return (n1 - n2);

        }

        public new int multi(int n1, int n2)

        {

            Console.WriteLine("the multiplication of number:{0}*{1}", n1, n2);

            return (n1 * n2);

        }

        public new int divide(int n1, int n2)

        {

            Console.WriteLine("the divide of number:{0}/{1}", n1, n2);

            return (n1 / n2);

        }  }


Don't want to miss updates? Please click the below button!

Follow MindStick