Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class of type <T> with nullable value of Type<T>

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?

like image 316
davy Avatar asked Dec 01 '22 17:12

davy


2 Answers

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.

like image 86
gzaxx Avatar answered Dec 04 '22 07:12

gzaxx


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.

like image 35
Obsidian Phoenix Avatar answered Dec 04 '22 06:12

Obsidian Phoenix