Why is the following forbidden?
Nullable<Nullable<int>>
whereas
struct MyNullable <T> { } MyNullable<Nullable<int>>
is NOT
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is because the struct constraint actually means ‘not nullable’ since Nullable, despite being a struct, is nullable (can accept the value null) the
Nullable<int>is not a valid type parameter to the outer Nullable.This is made explicit in the constraints documentation
If you want the rationale for that you would need the actual language designer’s comments on it which I can’t find. However I would postulate that:
Allowing the equivalent of int?? would only confuse that since the language provides no way of distinguishing Nullable
<Nullable<null>>and Nullable<null>nor any obvious solution to the following.Making that return true would be very complex and significant overhead on many operations involving the Nullable type.
Some types in the CLR are ‘special’, examples are strings and primitives in that the compiler and runtime know a lot about the implementation used by each other. Nullable is special in this way as well. Since it is already special cased in other areas special casing the
where T : structaspect is not such a big deal. The benefit of this is in dealing with structs in generic classes because none of them, apart from Nullable, can be compared against null. This means the jit can safely considert == nullto be false always.Where languages are designed to allow two very different concepts to interact you tend to get weird, confusing or down right dangerous edge cases. As an example consider Nullable and the equality operators
By preventing Nullables when using struct generic constraint many nasty (and unclear) edge cases can be avoided.
As to the exact part of the specification that mandates this from section 25.7 (emphasis mine):