.NET     Console.WriteLine( "All Things .NET" );
.NET Nerd Blog Home
2.28.2002

 

Fun with virtual, override, new, and base classes



I was asked last week: in c#, if I'm in a given derived class instance method, how would I call down to a method in the 2nd generation child of the class that I'm in?

class A { foo() {...} }
class B : A { foo() { ... } }
class C : B { foo() { <call down to A::foo here> } }


The c# keyword "base" allows you to reference anything in your base class (ctor, method, field, property, etc), but if you want to SKIP a base class in the derivation chain, you are out of luck --- as far as the base keyword is concerned.

base.base.Foo() doesn't work.



Turns out the answer is fairly simple - just have to go back to our c++ roots with casting.

((A)base).Foo() works just fine.



virtual, override, new

I know the rest of this is documented in and around the .NET community, but I like to have it here in once place for me to remember.

Given the following code, we will play with the 3 magical keywords and see what effect they have on the outcome of the program.


class BaseClass {
public void Identify() { Console.WriteLine("BaseClass::Identify"); }
}
class DerivedClass:BaseClass {
public void Identify() { Console.WriteLine("DerivedClass::Identify"); }

static void Main() {
DerivedClass test = new DerivedClass();
BaseClass b = test;
b.Identify();
}
}


--- new ---

This code as is generates a warning - keyword new is required because it hides inherited member.
The program will still run with these warnings, and b.Identify() will call the base class implementation (static binding at compile time). Adding "new" keyword gets rid of compiler warning, and the program results are the same.



--- virtual / override ---

Once we add the "virtual" keyword to the base class, we have a similar compile warning - ... hides inherited member. To make it override the implementation, add the override keyword, otherwise add the new keyword. Again, this program still runs despite this warning, but you get static compile time binding, which calls the base class function.
Add override to the derived method and all our problems are solved !!




Comments:
The bit of code where you cast the descendant to get to the ancestor is not valid. Just figured I'd post this (even on a post as old as this one) so no one chases red herrings.
 
Post a Comment

Powered by Blogger