How does the assignment of the null literal to a System.Nullable type get handled by .Net (C#)?

后端 未结 5 1902
情深已故
情深已故 2021-01-13 13:35

I was wondering if anyone knows how the C# compiler handles the following assignment:

int? myInt = null;

My assumption is that there is an

5条回答
  •  误落风尘
    2021-01-13 14:02

    What really happens is that when you assign null to the nullable type instance, the compiler simply creates a new instance of T?, using the default constructor (the initobj IL instruction on Jb answer), so the following two lines are equivalent:

    int? a = null;
    Nullable b = new Nullable();
    
    object.Equals(a,b); // true
    

    Therefore you cannot do this:

    Nullable c = new Nullable(null);
    

    Something similar happens then you compare a nullable type to null:

    if (a == null)
    {
      // ...
    }
    

    Behind the scenes it just does a call to the a.HasValue property.

提交回复
热议问题