3
using System;
public class C {
    public void Main() {
        
        int j1=5;
        int? j=7;
    }
}

Here is the IL code for initializing j1 and j

 IL_0000: nop
    IL_0001: ldc.i4.5
    IL_0002: stloc.0
    IL_0003: ldloca.s 1
    IL_0005: ldc.i4.7
    IL_0006: call instance void valuetype [System.Runtime]System.Nullable`1<int32>::.ctor(!0)

From the IL I can see that when I use Int32 no constructor gets called but when I use Nullable a constructor is called in order to put the value inside the variable.
Why is that so?
I can only imagine it is because the Nullable type must be able to be null but both non-nullable and nullable ints atre structs internally. So why isn't there a constructor in case of Int32?

All of this is taking into account Jon skeet's answer that when a nullable int32 is null, It does not point anywhere but It is null by Itself. ? (nullable) operator in C#

1
  • Note that the constructor is so short as to be most likely inlined, so performance-wise it shouldn't matter Commented Aug 27, 2022 at 22:17

1 Answer 1

3

Here is the Reference Source of struct Nullable<T>.

It has this constructor:

public Nullable(T value) {
    this.value = value;
    this.hasValue = true;
}

And the Value and HasValue properties are getter-only. This means that the constructor must be called to assign a value to a Nullable<T>.

There is no such thing like a stand-alone nullable 7 constant. Nullable<T> wraps the value assigned to it.

Btw., null is assigned by setting the memory position to 0 directly and bypassing the constructor according to Jb Evain's answer to: How does the assignment of the null literal to a System.Nullable type get handled by .Net (C#)?.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I was just wondering, the Nullable<int32> would you call it a refernce type(struct in this case) ?
It is a struct. So, no, it is a value type, i.e., a variable does contain its content directly and not a reference to an object.
Okay, soryy if I am asking silly questions. But if regular int is a struct as well then how does it get constructed without a constructor? I really apologize if the question is stupid.
Primitive types have special support in C#. See: Why C# implements integer type as a struct and not as a primitive type?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.