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