C# Override Method

Illustration

Virtual methods are meant to be re-implemented in derived classes. The C# language provides the override modifier for this purpose. This keyword specifies that a method replaces its virtual base method. It is critical to the construction of object-oriented programs.

Keywords

Whereas a virtual method introduces a new method, an override method specializes an existing inherited virtual method by providing a new implementation of that method. Hejlsberg et al., p. 469

Example

This program illustrates the difference between an override method in a derived class, and a method that is not an override method. The class A is the base class. It has the virtual method Y. In class B, we override Y; in class C, we implement Y but do not specify that it overrides the base method.

Virtual Method
Program that uses override modifier [C#]

using System;

class A
{
    public virtual void Y()
    {
	// Used when C is referenced through A.
	Console.WriteLine("A.Y");
    }
}

class B : A
{
    public override void Y()
    {
	// Used when B is referenced through A.
	Console.WriteLine("B.Y");
    }
}

class C : A
{
    public void Y() // Can be "new public void Y()"
    {
	// Not used when C is referenced through A.
	Console.WriteLine("C.Y");
    }
}

class Program
{
    static void Main()
    {
	// Reference B through A.
	A ab = new B();
	ab.Y();

	// Reference C through A.
	A ac = new C();
	ac.Y();
    }
}

Result

B.Y
A.Y
Question and answer

Main method. So what happens in the Main entry point? The A type is used to reference the B and C types. When the A type references a B instance, the Y override from B is used. When the A type references a C instance, though, the Y method from the base class A is used, not the C type. This is because the override modifier was not used. The C.Y method is local to the C type.

Warning

This is a warning

In the above program, the C type generates a warning because C.Y "hides" A.Y. This is the compiler's way of telling you your program is confusing and should be fixed. If you want C.Y to really "hide" A.Y, you can use the new modifier, as in "new public void Y()" in the declaration.

Summary

Object-oriented programming

The override modifier is necessary for properly implementing polymorphic behaviors in derived classes. You can actually re-implement a virtual base method, which will cause the base implementation to be ignored in favor of the "override" method. This polymorphic behavior is core to object-oriented design in many programs.

Method Tips
Dot Net Perls