Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 744
Nawaz Avatar asked Sep 29 '11 12:09

Nawaz


1 Answers

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).
like image 74
thecoop Avatar answered Oct 07 '22 03:10

thecoop