I have an interface<T>. This interface has a method Compare(T x, T y).
xcan never benull.yhas a large chance of beingnull.
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.
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 constrainingTto be astructor aclassdid not compile. That enabled the compiler to interpretT?clearly. That restriction was removed in C# 9.0, by defining the following rules for an unconstrained type parameterT:If the type argument for
Tis a reference type,T?references the corresponding nullable reference type. For example, ifTis astring, thenT?is astring?.If the type argument for
Tis a value type,T?references the same value type,T. For example, ifTis anint, theT?is also anint.If the type argument for
Tis a nullable reference type,T?references that same nullable reference type. For example, ifTis astring?, thenT?is also astring?.If the type argument for
Tis a nullable value type,T?references that same nullable value type. For example, ifTis aint?, thenT?is also aint?.For my question, this means I need to constrain
Tto a class, since I am on C#8.