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

Time:11-19

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.

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 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.

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.

  • Related