Reputation: 1825
given a class definition like:
public class Test<T>
{
T _value;
public void Test(T value)
{
_value = value;
}
public void DoStuff()
{
if(_value.HasValue)
{
//stuff
}
}
}
I would like to enforce that T is nullable so I can use the class like:
//does stuff
new Test<int?>(3).DoStuff();
//doesn't do stuff
new Test<int?>(null).DoStuff();
Upvotes: 4
Views: 763
Reputation: 11544
Nullable types are essentially derived from the type Nullable<T>
. Could you define your interface based upon Nullable<T>
?
Upvotes: 0
Reputation: 1500385
You can't enforce that T
itself is a nullable value type, no. You can enforce that T
is a non-nullable value type, however - and then use T?
everywhere in the class.
public class Test<T> where T : struct
{
T? _value;
public void Test(T? value)
{
_value = value;
}
public void DoStuff()
{
if(_value.HasValue)
{
//stuff
}
}
}
One other peculiarity is that you can't constrain T
to be any nullable type including reference types - and likewise you can't constrain T
to be any value type including nullable value types. The where T : class
constraint only works with classes (including delegate types) and interfaces, and the where T : struct
constraint only with non-nullable value types (including enums).
Upvotes: 6
Reputation: 1388
Yes, just use T?
or Nullable<T>
as type parameter.
Then your sample becomes:
//does stuff
new Test<int>(3).DoStuff();
//doesn't do stuff
new Test<int>(null).DoStuff();
Upvotes: 0