Search (Article Or Program)

11 September 2013

Easy Guide to Method Overriding in C#


Method Overriding in C#

When one class inherit from another class ,all the member of parent class become the member of child class .If there is a method of parent class that we want to predefined in child class. we can implement the concept of method overriding ,it means a method overriding of parents class and child class can have same method name with same parameter but parent class method will have "VIRTUAL"Keyword and child class method have "OVERRIDE"Keyword.


EXAMPLE:-
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
namespace methodoverriding
{
    class Program
    {
        static void Main(string[] args)
        {
            employee obj = new employee();
            obj.display();
            Console.ReadLine();
        }
    }
public class cls
{
    public virtual void display()
    {
        Console.WriteLine("hello");
    }
}
public class employee : cls
{
    public override void display()
    {
        Console.WriteLine("welcome");
    }
}
}

Description:- Here ,I have maked the object of employee class. The display method of only employee class will get in memory,because the "display method" of cls  class has been over-hidden by the employee class.

Follow these steps to run this program:-

Step1:- Open your visual studio and go File->New Project->Click Console Application.
See it:-



Step2:- copy the whole program code in program.cs file.
See it:-

Step3:-  Now Run the Application(Press F5).
OUTPUT:-


I hope this is helpful for you

ref: http://www.msdotnet.co.in/2012/06/method-overriding-in-c.html