Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Nullable<T> not match as a reference type for generic constraints [duplicate]

Possible Duplicate:
Nullable type as a generic parameter possible?

I came across a very weird thing with generic type constraints. I have a class like this:

public SomeClass<T> where T:class
{
}

However, I've found I can't use nullable types as I'd expect:

new SomeClass<int?>();

I get an error that int? must be a reference type. Is Nullable really just a struct with syntactic sugar to make it look like a reference type?

like image 885
Earlz Avatar asked Dec 10 '12 03:12

Earlz


People also ask

Which of the following generic constraints restricts the generic type parameter to an object of the class?

Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

What is a type parameter in C#?

The type parameter is a placeholder for a specific type that the client specifies when they create an instance of the generic type. A generic class cannot be used as-is because it is simply a blueprint for that type.


1 Answers

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

Nullable<T> is not just a struct with some syntatic sugar. It has special support in the CLR for some of its behavior. For example, it has special boxing behavior. Specifically, a nullable is never boxed. The underlying value is boxed. If the nullable is the null value (HasValue is false) then it is converted to a null reference. Also, conversion operators for any Nullable<T> to Nullable<U> are lifted from the conversions from T to U. These are features you wouldn't be able to implement yourself in .NET 1.0/1.1.

like image 174
Mike Zboray Avatar answered Sep 25 '22 00:09

Mike Zboray