articles

Home / DeveloperSection / Articles / Method overloadind and Method Overriding in C#

Method overloadind and Method Overriding in C#

Manish Kumar5857 13-Jan-2017

Method Overriding

Method Overriding is the feature of compile time Polymorphism.In Which More than One  Method name is same but have different parameter/Signature in the same Class. At Compile time the compiler check which one is going to be call. 

   staticvoid str(int x)
        {
            Console.WriteLine("interger");
        }
 
        staticvoid str(string y)
        {
            Console.WriteLine("string");
        }
       
        publicstaticvoid Main()
        {
            str("Mindstick");
        }
Out put :

Stirng

In this example I have maded two function with same name but given different parameter in first method it is of integer type and in another method I have given string type.When we compile this program it check first from the parameter given in the main function and it is of string type so it will call string type of method.

Method Overloading

Method Overloading is the feature of runtime polymorphism .In which more than one one method name is similar with same signature .But in different Classes.Method Overriding use two keywords that is Virtual and Override.Virtual in Base Class/Parent Class and Override in Inheritence Class/Child Class.It is Possible in Derived class only by the help of virtual or abstract keyword.

Let us take a example to understand Method Overriding

using System;
 
 namespace ConsoleApplication2
{
    classProgram
    {
        classParent
        {
            publicvirtualint balance()
            {
                return 10;
            }
            public Parent()
            {
              Console.WriteLine("Im in Parent Constructor");
            }
        }
 
        classChild : Parent
        {
            publicoverrideint balance()
            {
                return 20;
            }
 
 
            staticvoid Main(string[] args)
            {
                Child obj = newChild();               
                var val = obj.balance();
                Console.WriteLine(val);
                Console.Read();
 
 
 
            }
        }
 
 
       
      
    }
}


Output


Method overloadind and Method Overriding in C#



In the above example child class is inheriting parent class it have two method with same name and have same argument and from main class I have maken the object of class and called balace .


You can also visit these useful related post

Method Overloading and Overriding in C#

Method Overloading in C#

How is method overriding different from method overloading?

Why method overloading is not possible by changing the return type in java

Thank you..


Updated 07-Sep-2019

Leave Comment

Comments

Liked By