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.
The problem is that you are passing a nullable into your generic, and then trying to make it nullable.
Try this:
public class TestClass<T>
{
public T Value{ get; set; }
}
Now when you do this:
var x = new MyClass<int?>();
Value will be defined as int?
so you can use it in the way you want. If you define it as
var x = new MyClass<int>();
Value will be defined as int
- and won't accept nulls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With