Search code examples
c#nullablevaluetuple

Guarantee to return a non-empty tuple (non null fields) in C#


I wrote this code:

var (left, right) = A.FooWith(B);

where left, right, A and B are all Ts:

public class T {
// ...
  public (T left, T right) FooWith(T other)
  {
    T left = new (GetInfoFrom(this, other));
    T right = new (GetMoreInfoFrom(this, other));
    return (left, right);
  }
}

I know for sure that FooWith has to return a non null tuple with non null fields. But the compiler does not seem to see this, and it tells me that left is of type T?, and triggers warning down the code.

Is there a way to pass this information and prevent these warnings?


Solution

  • You need to specify type explicitly:

    (T left, T right) = A.FooWith(B);
    

    From the docs:

    When var is used with nullable reference types enabled, it always implies a nullable reference type even if the expression type isn't nullable. The compiler's null state analysis protects against dereferencing a potential null value. If the variable is never assigned to an expression that maybe null, the compiler won't emit any warnings. If you assign the variable to an expression that might be null, you must test that it isn't null before dereferencing it to avoid any warnings.

    Note that as stated null state analysis can determine that variable is not actually null (at least in "simple" cases):

    var (left, right) = A.FooWith(B);
    // left = null;
    Console.WriteLine(left.ToString()); // no warning if previous line is commented out