Click here to Skip to main content
11,719,903 members (88,298 online)
Click here to Skip to main content

Method Overriding in C#

, 9 May 2007 719.7K 2 89
Rate this:
Please Sign up or sign in to vote.
A tutorial on method overriding in C#

Introduction

Method overriding in C# is a feature like the virtual function in C++. Method overriding is a feature that allows you to invoke functions (that have the same signatures) that belong to different classes in the same hierarchy of inheritance using the base class reference. C# makes use of two keywords: virtual and overrides to accomplish Method overriding. Let's understand this through small examples.

P1.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();    
  }
}

Output

BC::Display

The above program compiles and runs successfully to give the desired output. It consists of a base class BC and a derived class DC. Class BC consists of function Display(). Class DC hides the function Display() it inherited from the base class BC by providing its on implementatin of Display(). Class Demo consists of entrypoint function Main(). Inside Main() we first create a reference b of type BC. Then we create an object of type BC and assign its reference to reference variable b. Using the reference variable b we invoke the function Display(). As expected, Display() of class BC is executed because the reference variable b refers to the object of class BC.

Now we add a twist of lime to the above program.

P2.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();    

     b = new DC();
     b.Display();    
  }
}

Output

BC::Display
BC::Display

Here we are creating an object of Derived class DC and storing its reference in the reference variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the function Display(). Since b contains a reference to object of type DC one would expect the function Display() of class DC to get executed. But that does not happen. Instead what is executed is the Display() of BC class. That's because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display() of class BC will be invoked, no matter whomb refers to. Take one more example.

P3.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();    

     b = new DC();
     b.Display();    

     b = new TC();
     b.Display();    
  }
}

Output

BC::Display
BC::Display
BC::Display

The output of the above program is a receipt of the fact that no matter to whom base class reference b refers, it invokes the functions of the class that matches its type. But doesn't this sound absurd? If b contains the reference to a perticular derived class object, then its supposed to invoke the function of that class. Well, C# helps us do this by the usage of keywords virtual and override as shown in the following program.

P4.cs

class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();    

     b = new DC();
     b.Display();    
  }
}

Output

BC::Display
DC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the Derived class's implementation of Display() is decorated with the modifier override. Doing so enables C# to invoke functions like Display() based on objects the reference variable refers to and not the type of reference that is invoking the function. Hence in the above program when b refers to the object of class BC it invokes Display() of BC and then when b refers to the object of class DC it invokes Display() of class DC. Let's see if this holds true for the third generation of derived classes. Take the following program.

P4.cs

class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{
  public override void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     BC b;
     b = new BC();
     b.Display();    

     b = new DC();
     b.Display();    

     b = new TC();
     b.Display();    
  }
}

Output

BC::Display
DC::Display
TC::Display

The above program compiles and runs successfully to give the expected desired output. The function Display() of Base class BC is declared as virtual, while the implementation of Display() in successive Derived classes is decorated with the modifier override. Next, we succesively create objects of each class and store their reference in base class reference variable b and invoke Display(). The rite versions of Display get invoked based on the object the reference variable refers to. Time for a tiny teaser! Guess what the output would be in the following program?

P5.cs

class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{

}

class Demo
{
  public static void Main()
  {
     BC b;

     b = new TC();
     b.Display();    
  }
}

Output

DC::Display

Since TC has no implementation of Display(), it inherits Display() from DC as TC is derived from DC. Hence Display() from Derived class DC gets executed. It's as if the derived class TC looked like this:

class TC 
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}
to the compiler. Take one more example. Guess what its output will be.

P6.cs

class BC
{
  public virtual void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public override void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{
  public new void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     BC b;

     b = new TC();
     b.Display();    
  }
}

Output

DC::Display

Agreed that TC defines its own new version of Display(). But its version of display is not invoked as Display() of TC does not override the Display() of the base class. With this understood we are done with Method overriding in C#.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Chetan Kudalkar
Software Developer (Senior)
India India
I am a Software engineer with around 7+ years of experience. Most of my experience is in Storage technology.

You may also be interested in...

Comments and Discussions

 
GeneralSimply Superb Pin
Mayank Kukadia26-Jun-15 9:23
memberMayank Kukadia26-Jun-15 9:23 
GeneralVery Good Explanation Pin
Kunal R. Khairnar1-Mar-15 22:41
memberKunal R. Khairnar1-Mar-15 22:41 
GeneralMy vote of 1 Pin
abhay5498-Jul-14 16:59
memberabhay5498-Jul-14 16:59 
QuestionMy Vote 5 Pin
niknishu18-May-14 8:05
memberniknishu18-May-14 8:05 
GeneralMy vote of 1 Pin
CrazyToCode20-Mar-14 23:10
memberCrazyToCode20-Mar-14 23:10 
Questioncomments Pin
Member 97211337-Jan-14 17:45
memberMember 97211337-Jan-14 17:45 
GeneralMy Vote of 5 Pin
Member 850226315-Dec-13 22:21
memberMember 850226315-Dec-13 22:21 
GeneralRe: My Vote of 5 Pin
Chetan Kudalkar16-Dec-13 7:04
memberChetan Kudalkar16-Dec-13 7:04 
GeneralNyc explanation... Pin
Atul Khanduri5-Dec-13 20:41
memberAtul Khanduri5-Dec-13 20:41 
GeneralMy vote of 5 Pin
innocent91027-Aug-13 20:45
professionalinnocent91027-Aug-13 20:45 
GeneralMy vote of 5 Pin
Amir Mohammad Nasrollahi11-Aug-13 21:41
professionalAmir Mohammad Nasrollahi11-Aug-13 21:41 
GeneralMy vote of 5 Pin
PravinSrinivasan14-Jun-13 4:16
memberPravinSrinivasan14-Jun-13 4:16 
QuestionComment Pin
Member 1005762927-May-13 20:59
memberMember 1005762927-May-13 20:59 
AnswerRe: Comment Pin
Atul Khanduri5-Dec-13 20:31
memberAtul Khanduri5-Dec-13 20:31 
GeneralMy vote of 4 Pin
Member6112-May-13 23:26
memberMember6112-May-13 23:26 
GeneralNice Pin
AVINCODE12-May-13 20:54
memberAVINCODE12-May-13 20:54 
GeneralMy vote of 5 Pin
Tirujit30-Apr-13 4:50
memberTirujit30-Apr-13 4:50 
QuestionNice explanation Pin
Member 849336819-Apr-13 2:30
memberMember 849336819-Apr-13 2:30 
AnswerRe: Nice explanation Pin
Atul Khanduri5-Dec-13 20:39
memberAtul Khanduri5-Dec-13 20:39 
QuestionGreat Pin
RobertoWhite2-Apr-13 3:03
memberRobertoWhite2-Apr-13 3:03 
AnswerRe: Great Pin
Atul Khanduri5-Dec-13 20:39
memberAtul Khanduri5-Dec-13 20:39 
GeneralExcellent Pin
Member 79050722-Apr-13 1:46
memberMember 79050722-Apr-13 1:46 
Questionexcellent explanation Pin
Shaswata27-Feb-13 19:51
memberShaswata27-Feb-13 19:51 
GeneralMy vote of 5 Pin
JoAnn Smith27-Feb-13 3:58
memberJoAnn Smith27-Feb-13 3:58 
Questionanil Pin
bindash20-Feb-13 6:37
memberbindash20-Feb-13 6:37 
AnswerRe: anil Pin
Atul Khanduri5-Dec-13 20:31
memberAtul Khanduri5-Dec-13 20:31 
GeneralMy vote of 5 Pin
Himanshu Luthra13-Feb-13 7:16
memberHimanshu Luthra13-Feb-13 7:16 
General. Pin
srikanth.aleti6-Jan-13 19:52
membersrikanth.aleti6-Jan-13 19:52 
GeneralMy vote of 4 Pin
Md. Humayun Rashed13-Dec-12 15:56
memberMd. Humayun Rashed13-Dec-12 15:56 
QuestionCan we override a method through a partial class Pin
Member 17978491-Nov-12 17:43
memberMember 17978491-Nov-12 17:43 
GeneralMy vote of 5 Pin
AppB4-Oct-12 18:31
memberAppB4-Oct-12 18:31 
GeneralMy vote of 5 Pin
girishmeena13-Sep-12 21:08
membergirishmeena13-Sep-12 21:08 
GeneralMy vote of 5 Pin
silicon_master13-Sep-12 18:06
membersilicon_master13-Sep-12 18:06 
GeneralMy vote of 4 Pin
sreenisha999-Sep-12 18:20
membersreenisha999-Sep-12 18:20 
GeneralMy vote of 4 Pin
Avi_Jai7-Sep-12 19:06
memberAvi_Jai7-Sep-12 19:06 
GeneralMy vote of 5 Pin
Member 82935573-Aug-12 21:26
memberMember 82935573-Aug-12 21:26 
GeneralMy vote of 5 Pin
RaviGupta798613-Jul-12 23:56
memberRaviGupta798613-Jul-12 23:56 
GeneralMy vote of 5 Pin
Maria Pradeep3-Jul-12 0:04
memberMaria Pradeep3-Jul-12 0:04 
GeneralRe: My vote of 5 Pin
Chetan Kudalkar3-Jul-12 9:45
memberChetan Kudalkar3-Jul-12 9:45 
Questionwell eplained Pin
hammadkhan0028-Jun-12 17:50
memberhammadkhan0028-Jun-12 17:50 
Questionvery nice examples... Pin
Asif Iqbal A.Khan6-Jun-12 19:41
memberAsif Iqbal A.Khan6-Jun-12 19:41 
QuestionVery Nice Pin
Ravindra_Parcha3-Jun-12 5:00
memberRavindra_Parcha3-Jun-12 5:00 
Suggestionwell explained Pin
satishmachineni29-Mar-12 20:04
membersatishmachineni29-Mar-12 20:04 
GeneralRe: well explained Pin
Chetan Kudalkar9-May-12 21:47
memberChetan Kudalkar9-May-12 21:47 
GeneralMy vote of 5 Pin
dipamzaveri1-Feb-12 16:49
memberdipamzaveri1-Feb-12 16:49 
GeneralMy vote of 5 Pin
Atulsinghal27-Dec-11 17:58
memberAtulsinghal27-Dec-11 17:58 
GeneralRe: My vote of 5 Pin
Chetan Kudalkar11-Jan-12 5:17
memberChetan Kudalkar11-Jan-12 5:17 
SuggestionMaking explnation more precise Pin
venkatesh.shapur16-Nov-11 18:11
membervenkatesh.shapur16-Nov-11 18:11 
GeneralRe: Making explnation more precise Pin
girishmeena13-Sep-12 21:06
membergirishmeena13-Sep-12 21:06 
GeneralMy vote of 4 Pin
Aravind Ramesh4-Nov-11 10:39
memberAravind Ramesh4-Nov-11 10:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150901.1 | Last Updated 9 May 2007
Article Copyright 2007 by Chetan Kudalkar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid