Search code examples
c#genericsnullablenon-nullablegeneric-constraints

Is it possible to define a "not Nullable<T>" constraint in a C# generic method?


In C#, the Nullable<T> type does not satisfy the where struct generic constraint (while AFAK this is techically a struct). This can be used to specify that the generic argument has to be a non-nullable value type :

T DoSomething<T>() where T : struct
{
   //... 
} 
DoSomething<int?>(); //not ok
DoSomething<int>();  //ok

And of course, Nullable<T> also does not satisfy the reference type where class constraint :

T DoSomething<T>() where T : class
{
   //...
} 
DoSomething<int?>(); //not ok
DoSomething<Foo>();  //ok

Is this possible to define a constraint such as it has to be a reference type or a value type but not a Nullable value type ?

Something like this :

void DoSomething<T>() where T : class, struct //wont compile!
{    
   //...   
} 
DoSomething<int?>(); //not ok
DoSomething<int>();  //ok
DoSomething<Foo>();  //ok

Solution

  • No, it's not possible on the declaration side. It's either struct OR class. However, you can check the typeof(T) at run-time to ensure T is Nullable<T2>

    Type type = typeof(T);
    if(Nullable.GetUnderlyingType(type) == null)
        throw new Exception();