Tuesday, February 24, 2009

Virtual vs Override vs Regular Methods in C#

In the world of C#, one of the biggest FAQ is what is the difference between a method marked as override and a method marked marked as virtual. The answer to this question is actually 10x easier when you think about how C# works. C# works by an automated compiler known as the CLR (in .NET implementation) where things are decided at compile time (when you build a program) or at run time (when your program is actually running).

When you mark a method as virtual, you are telling the CLR that when you use that method, whatever object you are using at run-time is the method you should use.

For example, lets say you have a ClassA with a Virtual method called VirtMethod(). ClassB inherits from ClassA and has an Override method of the VirtMethod(). Because you marked ClassA as a virtual method, whenever you call VirtMethod(), the CLR waits until the actual code is executed to see if the VirtMethod() has been overridden by ClassB's VirtMethod().

ClassA MyClassA = new MyClassA();
ClassA MyClassB = new MyClassB();

MyClassA.VirtMethod(); //CLR sees that ClassA
virtual method is the only one there and thus
uses it.
MyClassB.VirtMethod(); //CLR notices that ClassB
has an override for ClassA. So it uses that.

For a regular method without anything behind it, the method you have at compile time is used. It doesn't matter what happens at run time. In fact, if you try an override a normal non-virtual method, a compile error will occur.

This is seen in 10.6.4 of the C# v 3.0 Specifications: "A compile-time error occurs unless all of the following are true for an override declaration:........The overridden base method is a virtual, abstract, or override method. In other words, the overridden base method cannot be static or non-virtual."

More information about the differences of the Virtual Method and the Override Method and a Plain Method can be found in section 10.6.3 - 10.6.4 of the C# v3.0 specifications. I highly recommend you all read that guide since it's very useful in telling you how things are suppose to work.

0 comments:

Post a Comment

 
Copyright 2008 - 2009 by WDO Enterprises LLC - All Rights Reserved