class Test<T>
{
T? obj;
}
Error:
The type ‘T’ must be a non-nullable value type in order to use it as
parameter ‘T’ in the generic type or method ‘System.Nullable’
I need to keep a possibly null reference to type T, but T can be either a value type or a reference type, and you can’t have Nullable<T> if T is a reference type. Any solution?
If you need to support both classes and structs inside
Test<T>, you could not use thewhere T : structconstraint and you would not be able to support theT?directly, although you could achieve the desired effect via the semantics of whatT?does.So where you would use
obj, you would first checkhasValueto see if it is in a usable state (“non-null”).You could go a step further and encapsulate this to essentially roll your own nullable wrapper (perhaps nest it inside
Testso as to not make it part of the publicly visible API) to support both classes and reference types. While it would be redundant, it would bring together the currently separate concepts of a null class and null struct.