I have the need to make a class that can hold the value for the following types: int?, decimal?, date, bool? string
.
I want to be able to do soemthing like:
var x = new MyClass<int?>()
x.Value = null;
x.value = 99;
// or
var y = new MyClass<bool?>();
y.Value = null;
y.Value = true
// and so on
I have been trying to create a class of type T along the lines of:
public class TestClass<T>
{
public T? Value{ get; set; }
}
I want to use Value to take any of the allowed types but I can't make T nullable. The error is:
Only non nullable value type could be underlying of Sysytem.Nullable
is there anyway of doing what I'm trying to achieve?
Try this:
public class TestClass<T> where T : struct
{
public T? Value{ get; set; }
}
Classes cannot be nullable as class is a reference type. You have to add constraint to your generic class to allow only structs (which can be nullable).
string
is a reference type and your class won't work with string
it this case as it can't be nullable.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments