What Virtual and Override do behind the scenes

I just realized what Virtual and Override is used for (I can't use it for a long time). Now I use them in Factory templates. So my question is what does Virtual and Override do behind the scenes? I am ready to join IL and machine code.

+7
override c # virtual
source share
3 answers

I cannot give you any details on how this is done in IL, but the basic theory is simple.

When the compiler sees a virtual method declaration, instead of attaching a method to a class, it adds it to what is called a vtable (virtual table method) for this class, which contains pointers to functions.

Now, since vtable is part of the class, it is inherited by subclasses, and thus virtual methods are also inherited. Now comes the override bit. When the compiler sees an override in a method declaration, it searches for a vtable , finds a method to override, and changes the function pointer to point to the new definition.

Thus, you get both the inheritance of methods from the parent classes, and the ability to change their definitions in the child classes.

See the Wikipedia article in the Virtual Method Table for more information.

+15
source share

You do not need to go into IL - virtual and override embrace the well-known concept of object orientation called polymorphism . It is effective when access to a polymorphic method or property, which method / property is really applied, is determined only at runtime. Under the hood, basically, the correct method (in the case of a property, it is also a method) is determined by referring to the virtual method table - the lookup table to find the correct method based on the type of runtime.

+4
source share

If you are interested in IL, use ildasm.exe to view the compiled program (DLL or EXE). You will see that the methods that you mark as "virtual" are simply referred to as "virtual" in IL.

Magic happens at runtime. The CLR creates a “method dispatch table” (or “virtual method table”) that it uses to look for class methods in memory. To resolve polymorphism, where the same method name means different things depending on the type of runtime, some additional search is needed for virtual methods. (We can say that they are called “virtual” methods precisely because they are chosen “worthily” of what they are working on, but they are watching @Pavel's comments.) Joe Duffy put it this way:

A virtual method call is much like a regular call, except that it must look up the purpose of the call at runtime based on the 'this' object.

These are the basics. Don Boxing is a good read if you really want to go further with this.

+4
source share

All Articles