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.
CodePudding user response:
I found the answer in a document suggested by @PanagiotisKanavos:
https://docs.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
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 T to a class, since I am on C#8.
CodePudding user response:
Given that till this answer is written, it's not mentioned that if there is a condition on T like this
public interface IDoWork<T> : where T: ???
{...}
we'll assume it to be a reference type
Now that it's assumed that T is a reference type then you should do this
public int Compare(T x, T y)
{
if (y == null)
//Take decision accordingly.
else
//Take decision accordingly.
}
Compare methods do not take parameters as nullable types. They take pure instances and then inside the method decide according to the expected behaviour.
