Nawaz Nawaz - 28 days ago 7
C# Question

Why can't I write Nullable<Nullable<int>>?

The definition of

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

Answer

From section 4.1.10 of the C# language spec:

A non-nullable value type conversely is any value type other than System.Nullable<T> and its shorthand T? (for any T), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with a struct constraint). The System.Nullable<T> type specifies the value type constraint for T (ยง10.1.5), which means that the underlying type of a nullable type can be any non-nullable value type. The underlying type of a nullable type cannot be a nullable type or a reference type. For example, int?? and string? are invalid types.