The definition of Nullable<T>
is:
[SerializableAttribute]
public struct Nullable<T> where T : struct, new()
The constraint where T : struct
implies that T
can only be a value type. So I very well understand that I cannot write:
Nullable<string> a; //error. makes sense to me
Because string
is a reference type, not a value type. But I don't really understand why can't I write
Nullable<Nullable<int>> b; //error. but why?
Why is it not allowed? After all, Nullable<int>
is a value-type, and therefore, it can be type argument to Nullablle<T>
.
When I compiled it on ideone, it gives this error (ideone):
error CS0453: The type 'int?' must be a non-nullable value type in order to use it as type parameter 'T' in the generic type or method 'System.Nullable' Compilation failed: 1 error(s), 0 warnings
Because it's in the C# spec (section 4.4.4):
If the constraint is the value type constraint (struct), the type A must satisfy one of the following:
- A is a struct type or enum type, but not a nullable type. Note that System.ValueType and System.Enum are reference types that do not satisfy this constraint.
- A is a type parameter having the value type constraint (§10.1.5).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With