How does a Nullable type work behind the scenes?

后端 未结 4 1952
一个人的身影
一个人的身影 2020-12-15 08:41

I\'m curious to know how the Nullable type works behind the scenes. Is it creating a new object(objects can be assigned null) with a possible value of null?

In the

4条回答
  •  猫巷女王i
    2020-12-15 09:13

    It's actually quite simple. The compiler gives you a hand with the syntax.

    // this
    int? x = null;
    // Transformed to this
    int? x = new Nullable()
    
    // this
    if (x == null) return;
    // Transformed to this
    if (!x.HasValue) return;
    
    // this
    if (x == 2) return;
    // Transformed to this
    if (x.GetValueOrDefault() == 2 && x.HasValue) return;
    

提交回复
热议问题