Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>For this reason, .NET's sealed classes can have better method dispatching performance than their non-sealed counterparts.</p> </blockquote> <p>Unfortunately this is not the case. Callvirt does one other thing that makes it useful. When an object has a method called on it callvirt will check if the object exists, and if not throws a NullReferenceException. Call will simply jump to the memory location even if the object reference is not there, and try to execute the bytes in that location.</p> <p>What this means is that callvirt is always used by the C# compiler (not sure about VB) for classes, and call is always used for structs (because they can never be null or subclassed).</p> <p><strong>Edit</strong> In response to Drew Noakes comment: Yes it seems you can get the compiler to emit a call for any class, but only in the following very specific case:</p> <pre><code>public class SampleClass { public override bool Equals(object obj) { if (obj.ToString().Equals("Rubber Ducky", StringComparison.InvariantCultureIgnoreCase)) return true; return base.Equals(obj); } public void SomeOtherMethod() { } static void Main(string[] args) { // This will emit a callvirt to System.Object.Equals bool test1 = new SampleClass().Equals("Rubber Ducky"); // This will emit a call to SampleClass.SomeOtherMethod new SampleClass().SomeOtherMethod(); // This will emit a callvirt to System.Object.Equals SampleClass temp = new SampleClass(); bool test2 = temp.Equals("Rubber Ducky"); // This will emit a callvirt to SampleClass.SomeOtherMethod temp.SomeOtherMethod(); } } </code></pre> <p><strong>NOTE</strong> The class does not have to be sealed for this to work.</p> <p>So it looks like the compiler will emit a call if all these things are true:</p> <ul> <li>The method call is immediately after the object creation</li> <li>The method is not implemented in a base class</li> </ul>
 

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