Does anyone know why this code doesn't compile?
Nullable<Nullable<int>> n = null;
I realize Nullable has a constraint
where T : struct
But Nullable is struct. I also know this constraint has a restriction "The type argument must be a value type. Any value type except Nullable can be specified." (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters). So how does it work? Is this solved on compiler level?
The error message is:
The type
int?
must be a non-nullable value type in order to use it as parameter 'T' in the generic type or methodNullable<T>
So it must not only be a value type but a non-nullable value type. But Nullable<int>
is a nullable value type.
Here's the compiler error CS0453 which also shows this example:
This error occurs when you use a non-value type argument in instantiating a generic type or method which has the value constraint on it. It can also occur when you use a nullable value type argument.
Q: Is this solved on compiler level?
Yes, which means it' not very interesting to know how they achieved this constraint. It's an implementation detail of the compiler which doesn't need to use a C# language feature.
Why is not allowed?
Well, what would be the benefit of a Nullable<Nulable<int>>
? Nullables were introduced to give value types the opportunity to be null
(so undefined, without value). This is already achieved for a Nullable<int>
, it can be null
. So by nesting it in another nullable you would not get anything. It's not allowed for the same reason why you can't have a Nullable<string>
, a string as every other reference type can already be null
.
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