Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the case where you have a virtual method on a sealed class, and the type of the object reference is the sealed class the virtual call could be avoided. Take the following example. There is no actual reason that GetName needs to be called virtually because we know there can be no sub class of Parent and hence no further virtual dispatch. </p> <pre><code>sealed class Parent : Child { public override string GetName() { return "foo"; } } public void Test() { var p = new Parent(); var name = p.GetName(); } </code></pre> <p>A compiler could choose to notice this and output a call IL instruction instead of a callvirt. However both the C# and VB.Net Compiler choose not to perform this optimization. Both will emit callvirt. </p> <p>The JIT is also free to make such an optimization. It also chooses not to. </p> <ul> <li><a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2007/02/27/JIT-Optimizations_2C00_-Inlining_2C00_-and-Interface-Method-Dispatching-_2800_Part-1-of-N_2900_.aspx" rel="noreferrer">http://blogs.microsoft.co.il/blogs/sasha/archive/2007/02/27/JIT-Optimizations_2C00_-Inlining_2C00_-and-Interface-Method-Dispatching-_2800_Part-1-of-N_2900_.aspx</a></li> </ul> <p>That does not mean however that you should not seal your classes. Classes should be sealed unless you actually intend for someone to inherit from them. Otherwise you're opening yourself up to scenarios you have failed to accurately cost. </p> <p>Additionally, there's nothing stopping the compilers and JIT from implementing this at a later date. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload