Search code examples
c#genericsnull-conditional-operator

C# Is there a way to put a Null-conditional operator (?) on T?


I have an interface<T>. This interface has a method Compare(T x, T y).

  • x can never be null.
  • y has a large chance of being null.

I want to make this clear by using the Null-conditional operator ? on y: Compare(T x, T? y).

Is this possible and from what version of C#?

EDIT:

T can be a reference type and a value type.


Solution

  • I found the answer in a document suggested by @PanagiotisKanavos:

    https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references#generics

    In C# 8.0, using T? without constraining T to be a struct or a class did not compile. That enabled the compiler to interpret T? clearly. That restriction was removed in C# 9.0, by defining the following rules for an unconstrained type parameter T:

    • If the type argument for T is a reference type, T? references the corresponding nullable reference type. For example, if T is a string, then T? is a string?.

    • If the type argument for T is a value type, T? references the same value type, T. For example, if T is an int, the T? is also an int.

    • If the type argument for T is a nullable reference type, T? references that same nullable reference type. For example, if T is a string?, then T? is also a string?.

    • If the type argument for T is a nullable value type, T? references that same nullable value type. For example, if T is a int?, then T? is also a int?.

    For my question, this means I need to constrain T to a class, since I am on C#8.