.NET Inside Out Part 11 — Using structs for devirtualization

This is the eleventh part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

Last time we saw how type markers can result in code optimizations because .NET knows types with structs and can get rid of some code. Today we are going to see that it can actually devirtualize calls.

Let’s get this code:

Generic method for value types must be JITted differently than for normal reference types. This is the code of Main method:

We see that call to C.Foo() was inlined and we print to the output directly. If you now change it to

You get the following Main:

So you can see the direct call to the final implementation.