Search code examples
c#oopinheritancevtablesealed

How to get rid of virtual table? Sealed class


As far as I know making class sealed gets rid of look up in VTable or am I wrong? If I make a class sealed does this mean that all virtual methods in class hierarchy are also marked sealed?

For example:

public class A {
    protected virtual void M() { ........ }
    protected virtual void O() { ........ }
}

public sealed class B : A {
    // I guess I can make this private for sealed class
    private override void M() { ........ }
    // Is this method automatically sealed? In the meaning that it doesn't have to look in VTable and can be called directly?

    // Also what about O() can it be called directly too, without VTable?
}

Solution

  • "I guess I can make this private for sealed class"

    You can't change access modifier in inheritance hierarchy. It means if method is public in base class you can't make it private or internal or protected in derived classes. You can change modifier only if you declare your method as new:

    private new void M() { ........ }
    

    As far as I know making class sealed gets rid of look up in VTable or am I wrong?

    Sealed class is last in hierarchy because you can't inherit from it. Virtual table can be used with sealed class in case this sealed class overrides some method from base class.

    If I make a class sealed does this mean that all virtual methods in class hierarchy are also marked sealed?

    You can see IL code:

    .method family hidebysig virtual            // method is not marked as sealed
        instance void M () cil managed 
    {        
        .maxstack 8
    
        IL_0000: nop 
        IL_0001: ret value
    }  
    

    Method is not marked as sealed. Even if you explicitly mark this method as sealed you will get the same IL code.

    Also, there is no reason to mark method as sealed in sealed class. If class is sealed you can't inherit it so, you can't inherit it's methods.

    About virtual tables - if method is overriding and you delete it from virtual table you can never use it in inheritance hierarchy so, there is no reason to override method and never use it in inheritance hierarchy.