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#
CodePudding user response:
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#)?.
CodePudding user response:
The ? operator is just syntactic sugar for the creation of a Nullable Object.
Your code
int? j7 = 7
Is exactly the same as
Nullable<Int> j7 = new Nullable<Int>(7)
For value types c# does not call constructors/create Objects. Nullable is not a value type but a reference type, Int32 is a value type.