Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overridden virtual method in C#

Tags:

c#

In "The C# Programming Language" book Eric Lippert mentioned this:

A subtle point here is that an overridden virtual method is still considered to be a method of the class that introduced it, and not a method of the class that overrides it.

What is the significance of this statement? Why does it matter if the overridden virtual method is considered to be a method of the class that introduced it (or otherwise) since the overridden method will never be called unless you are dealing with the derived class?

like image 701
Boon Avatar asked Sep 15 '25 21:09

Boon


1 Answers

It matters when you have a reference of one type pointing to an object of a different type.

Example:

public class BaseClass {
  public virtual int SomeVirtualMethod() { return 1; }
}

public class DerivedClass : BaseClass {
  public override int SomeVirtualMethod() { return 2; }
}

BaseClass ref = new DerivedClass();
int test = ref.SomeVirtualMethod(); // will be 2

Because the virtual method is a member of the base class, you can call the overriding method with a reference of the base class type. If it wasn't, you would need a reference of the derived type to call the overriding method.

When you are shadowing a method instead of overriding it, the shadowing method is a member of the derived class. Depending on the type of the reference you will be calling the original method or the shadowing method:

public class BaseClass {
  public int SomeMethod() { return 1; }
}

public class DerivedClass : BaseClass {
  public new int SomeMethod() { return 2; }
}

BaseClass ref = new DerivedClass();
int test = ref.SomeMethod(); // will be 1

DerivedClass ref2 = ref;
int test2 = ref2.SomeMethod(); // will be 2
like image 106
Guffa Avatar answered Sep 17 '25 11:09

Guffa