Search code examples
c#genericsc#-8.0nullable-reference-types

What does class? (class with question mark) mean in a C# generic type constraint?


While I tried to find an answer to another question I noticed that this code compiles in C#:

public void Foo<T>(T obj)
    where T : class?
{
}

I did not manage to find in the documentation what it even means.


Solution

  • It enforces that T has to be a nullable reference type.

    The type you set in for T, must derive from object?.

    It's a new feature in C#8, to explictly declare a type as nullable. if you have

     Add<T>(T tmp);
    

    You document, it's OK to Add null;