Why Nullable <T> Doesn't Match Reference Type for General Constraints

Possible duplicate:
Is a null type as a general parameter possible?

I met a very strange thing with general type restrictions. I have a class like this:

public SomeClass<T> where T:class { } 

However, I found that I could not use types with a null value, as I expected:

 new SomeClass<int?>(); 

I get an error, what is int? must be a reference type. Is Nullable really just a syntax sugar structure to make it look like a reference type?

+14
generics c # nullable reference-type
Dec 10 '12 at 3:20
source share
1 answer

Nullable<T> is a struct (see MSDN ), however it is the only struct that does not satisfy the struct . Therefore, when using class or struct constraints, you cannot use the Nullable parameter as a parameter of a general type.

Nullable<T> is not just a structure with some syntactic sugar. He has special support in the CLR for some of his activities. For example, he has a special behavior in boxing. In particular, a nullable value is never boxed. The base value in the box. If nullable is a null value (HasValue is false), then it is converted to a null reference. In addition, conversion operators for any Nullable<T> to Nullable<U> are removed from conversions from T to U You cannot implement these functions in .NET 1.0 / 1.1.

+19
Dec 10
source share



All Articles