Is it possible to ensure that the type parameter is zero for the class

based on the class definition:

public class Test<T> { T _value; public void Test(T value) { _value = value; } public void DoStuff() { if(_value.HasValue) { //stuff } } } 

I would like to indicate that T is NULL, so I can use the class:

 //does stuff new Test<int?>(3).DoStuff(); //doesn't do stuff new Test<int?>(null).DoStuff(); 
+4
source share
4 answers

You cannot guarantee that T itself is a NULL value type, no. However, you can ensure that T an unimaginable value type, but then use T? everywhere in the classroom.

 public class Test<T> where T : struct { T? _value; public void Test(T? value) { _value = value; } public void DoStuff() { if(_value.HasValue) { //stuff } } } 

Another feature is that you cannot limit T any type of NULL, including reference types, and you cannot limit T to any type of value, including types of NULL values. The where T : class constraint only works with classes (including delegate types) and interfaces, and with the where T : struct constraint only with value types that are not null values ​​(including enumerations).

+6
source

Yes, just use T? or Nullable<T> as a type parameter.

Then your sample will look like this:

 //does stuff new Test<int>(3).DoStuff(); //doesn't do stuff new Test<int>(null).DoStuff(); 
0
source

You can try: -

 public class Test<Nullable<T>> 
0
source

Nullable types are essentially derived from the Nullable<T> . Could you define your interface based on Nullable<T> ?

0
source

All Articles