I just came to understand Virtual and Override is use for(I can't find a use for so long). Now I'm using them in Factory Patterns. So my question is what does Virtual and Override do behind the scene? I'm willing to go in to IL and Machine code stuff.
I cannot give you any insights as to how it is done in IL but the basic theory is simple.
When the compiler sees a virtual method declaration, instead of attaching the method to the class, it adds it to what is called a vtable
(a Virtual Method Table) for that class, which holds pointers to functions.
Now since the vtable
is a part of the class, it is inherited by its subclasses and thus the virtual methods are inherited as well. Now comes the override bit. When the compiler sees an override in a method declaration, it looks up the vtable
, finds the method to override and changes the function pointer so that it points to the new definition.
Thus, you get both an inheritance of methods from parent classes and the ability to change their definitions in child classes.
For more information, see the Wikipedia article on the Virtual Method Table.
You don't need to go into the IL - virtual
and override
encompass a well-known object orientation concept known as polymorphism. Effectively, when a polymorphic method or property is accessed, which method/property actually applies is only determined at runtime. Under the bonnet, basically, the correct method (in the case of a property, it's a method as well) is determined by accessing a virtual method table - a lookup table for finding the right method, based on the runtime type.
If you're interested in the IL, use ildasm.exe to look at a compiled program (DLL or EXE). You'll see that the methods you mark as "virtual" are simply marked as "virtual" in the IL.
The magic happens in the runtime. The CLR builds a "method dispatch table" (or "virtual method table"), which it uses to locate your class's methods in memory. In order to allow polymorphism, where the same method name means different things depending on runtime type, some additional lookup is required for virtual methods. (One could say they're called "virtual" methods precisely because they are selected "by virtue" of what they are operating on — but see @Pavel's comments.) Joe Duffy put it this way:
A virtual method call is very much like an ordinary call, except that it must look up the target of the call at runtime based on the 'this' object.
Those are the basics. Don Box is good reading if you really want to go further with this.