ALT-Coder trait explained: C# Virtual properties / Methods

When breaking into the OOP / Alt-Coder world, you’ll often see a lot of virtual methods and properties thrown around and clever people talking about them rather matter of factly, for instance at Ayende @ Rahien wishing for a virtual keyword option added in the next version of Resharper. If coming from a Java background or just trying to grok its use from scattered code snippets or funkless tech posts all this virtual stuff can be a bit perplexing. Fear not.

So, here it is. The quickest, simplest unperplexification of the virtual keyword in C# that I can muster. No foo, bar, baz needed.

–The boring but clear bit —————————–
Virtual methods and properties in base classes REQUIRE derived classes to use the ‘override‘ keyword when, well, overriding said methods and properties. If these base methods and properties on the other hand are not marked as virtual, then when you write something in a derived class with the same name and signature, you are not in fact overriding the base version, but instead just ‘hiding’ it with functionality with the same name.
——————————————————————-
What’s the practical difference you say?

Funny you should ask…..
Monkey Speak() not being called.
If you have a specific derived class in your hand, say the Monkey class derived from the base of Animal, and you know damn well you have a Monkey in your hand because you made a new() Monkey, the answer is the ever popular “nothing”. The Monkey’s Speak() method for instance will get run when you ask it to with the expected results (Probably OOK in my experience).

If however, you are using an AnimalFactory to create Animals willy nilly, or are passing around other unknown Animal objects in general, the difference becomes apparent.

Situation A - virtual keyword is used

If a base Animal method or property is marked virtual, and you call said method or property on some unknown Animal, C# will see which kind of animal you really have a hold of and call ITS designated overridden version.

Ex. If it so happens that the unknown Animal you have in your hand turns out to be a Monkey, and Monkey overrides Speak(), an OOK is OOKed.

vs.

Situation B - virtual keyword is not used

If however your Animal Speak() method is NOT marked as virtual (which is the default unless you put it there) and you call the method at the generic, unknown Animal level, the Animal version will run, non-descriptively grunting perhaps, and C# won’t bother to see what actual kind of Animal you have in your hand. If, unbeknownst to you, you actually had a Monkey in your hand also having a Speak() method but not explicitly ‘overriding’ the Speak() of the Animal it won’t make a difference. Your special monkey abilities go unnoticed. Terrible.

–Duncan

[****Addendum per Oren’s Comment ****]

Oren wisely brings up that maybe it would be reasonable to talk about what you can actually do with virtuals* vs. the way they behave. OK, here goes.

A stab at Interception:

Once you find yourself in the ever-exciting world of events, event handers, and delegates you will inevitably have to come to grips with the fact that invoking an event can only be done from within the class that declared the event to begin with. If you are writing a general base component resplendent with its own events that you foresee being subclassed down the line, chances are you’d like those subclasses to be able to invoke those events as well. To accomplish this, you can add a protected method who’s job it is to invoke the event, so that derived classes now have a way to fire off said event which would otherwise remain unattainable and aloof, like that girl who sat across the row from you in 9th grade Calculus.

So, to recap, the event is hidden to subclasses, so we make a go-between that can be derived.

Here’s where the virtual comes in. As we’ve already seen, by making that event-invoker method virtual, you have the opportunity to override it in your derived class it and be assured that your distinct flavor of that invoker gets run, even when the calling client isn’t sure of if they are dealing with the base or your derived version. By having the standard operating procedure be that your method invoker is the way everyone is going to invoke your events, your derived class gets to intercept the events invoked on the base class which would be otherwise unattainable at that subclassed level.

Something less complex, like say a property, benefits in a similar way. Lets say the derived class’ property has more to it than just a pedestrian getter / setter for a string. Perhaps some math is performed on an integer when set, or a week added when a DateTime is set, which is different from what happens in the base class. By virtue of those properties being virtual in a the base class, the derived class gets to again intercept the processing that happens when the property is accessed or set, guaranteeing your custom logic is followed, no matter how little your client may know about what specific type of derived object it actually has a handle on.

*Admittedly some clever details of this topic may be better tackled by others so if you have 2 cents to add, please feel free to do so. Given the dearth of ‘fun’ material about this on the web, this may very well be where folks land after googling ‘C# virtual methods’, so your help counts!

kick it on DotNetKicks.com

7 comments ↓

#1 Ayende Rahien on 06.06.07 at 12:41 am

You need to continue this with a discussion of what you can do with virtuals (interception)

#2 Duncan on 06.07.07 at 8:52 pm

Oren, Good point. I’ve thrown up an addendum per your comment. We’ll see how it flies….

#3 Nick Eve on 06.18.07 at 5:51 pm

As a longtime friend, it is sad to see you still don’t understand that a chimp is an ape, not a monkey.

#4 Duncan on 06.18.07 at 7:14 pm

I plead ‘google image search’. Apes evidently are much more difficult to monetize clip-art wise, … perhaps the real travesty. I will however endeavor to fact check my primates going forward.

#5 Polermo on 11.20.07 at 5:06 pm

Primates are jolly creatures. However, I find it unwise to leave an uncensored image of naked apes on the net. God knows who will look at it and before you know it you’re in trouble.
Still, I must say your essay on Virtual Methods is quite educating to say the least. I feel good about myself and my family. Virtual Methods will assist me and my kids in succeeding in life. Thank you Microsoft.

#6 JoelP on 03.21.08 at 4:50 pm

Very helpful. Thanks!

#7 DonnieH on 07.16.08 at 12:16 am

Perhaps the best monkey porn/virtual keyword explanation on the web. One stop shopping at its finest, Thanks Duncan!

Leave a Comment