Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor called when instatiating a nullable value type

Tags:

c#

nullable

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#

like image 402
Jason9789 Avatar asked Aug 25 '26 17:08

Jason9789


1 Answers

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

like image 73
Olivier Jacot-Descombes Avatar answered Aug 28 '26 06:08

Olivier Jacot-Descombes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!