Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable restrictions [duplicate]

Tags:

c#

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?

like image 520
srv52 Avatar asked Sep 06 '17 12:09

srv52


1 Answers

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 method Nullable<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.

like image 68
Tim Schmelter Avatar answered Nov 17 '22 02:11

Tim Schmelter