.NET Inside Out Part 19 – Creating structure instance without calling a constructor

This is the nineteenth 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#

Today we will see that .NET can create an instance of a structure without calling its constructor if it is not needed.

Let’s take this code:

Structure with integer field. Then, two methods creating a structure and returning its field. The difference is first method returns directly, second method stores in a variable. Let’s see IL:

We can see that we create an instance using newobj. Second method:

And magic, this time we don’t create an instance, we just call the constructor. This is optimization on the IL level. If we check jitted code in debug mode:

We can see there are differences (reflecting differences in IL). However, in Release:

It works in the same way.