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#

Jason9789
  • 295
  • 1
  • 9

1 Answers1

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#)?.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Thank you, I was just wondering, the Nullable would you call it a refernce type(struct in this case) ? – Jason9789 Aug 27 '22 at 13:14
  • 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. – Olivier Jacot-Descombes Aug 27 '22 at 14:02
  • 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. – Jason9789 Aug 27 '22 at 15:24
  • Primitive types have special support in C#. See: [Why C# implements integer type as a struct and not as a primitive type?](https://stackoverflow.com/a/40845063/880990). – Olivier Jacot-Descombes Aug 28 '22 at 14:53