Why can't I write Nullable>?

前端 未结 5 1160
陌清茗
陌清茗 2020-12-06 17:16

The definition of Nullable is:

[SerializableAttribute]
public struct Nullable where T : struct, new()

The constraint

5条回答
  •  盖世英雄少女心
    2020-12-06 17:55

    This isn't exactly an answer, but just food for thought.

    Round 1

    Nullable> a;

    error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

    Intellisense hints... The name can be simplified


    Round 2

    Nullable a;

    error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'

    Intellisense hints... The name can be simplified


    Round 3

    int?? a;

    error CS1519: Invalid token '??' in class, struct, or interface member declaration

    error CS1525: Invalid expression term '??'


    Conclusion

    int? is essentially just a short-hand evaluation of Nullable, but there's no such thing as int?? which is the only way I can see of representing Nullable> in short-hand. Plus int?? borrows the null-coalescing operator, so I'm glad it's not possible because it looks dreadful. Imagine int????????????? a; How pointless.

    Finally, since the reference source for Nullable does not yield any constraints for enforcing this, my guess is that this constraint was baked into the CLR as a special case when nullable value types were introduced into C#.

提交回复
热议问题