Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable generic field in generic class

I'm trying to do something like this:

public class MySuperCoolClass<T>
{
    public T? myMaybeNullField {get; set;}
}

Is this possible?

This gives me the error:

error CS0453: The type T' must be a non-nullable value type in order to use it as type parameterT' in the generic type or method System.Nullable'.

Thanks

like image 491
Vesuvian Avatar asked Nov 22 '25 11:11

Vesuvian


1 Answers

Add where T : struct generic constraint to get rid of the error since Nullable<T> accepts only struct.

public class MySuperCoolClass<T> where T : struct
{
    public T? myMaybeNullField { get; set; }
}

Nullable<T> is defined as below

public struct Nullable<T> where T : struct

So you're also forced to do so, just to prevent you from doing MySuperCoolClass<object> which makes object? which is not valid.

like image 68
Sriram Sakthivel Avatar answered Nov 25 '25 02:11

Sriram Sakthivel