1

I have a function that returns a nullable result and has an out parameter that is also nullable:

public Result? GetResult(out Parameter? parameter)
{
    Result? result = //...get the result somehow

    if (result is not null)
    {
        //...do stuff
        parameter = something;
        return result;
    }
    
    parameter = null;
    return null;
}

Is there a way to use the attribute NotNullIfNotNull in parameter but regarding whether result is not null?

Something like:

public Result? GetResult([NotNullIfNotNull(return)] out Parameter? parameter)

I want to avoid having to check both result and parameter for null outside the function.

6
  • 2
    You could make them both out parameters and return true if they're both not null, then you can put [NotNullWhen(true)] on both output parameters. Test the return value and use both with impunity if it's true. Addressing the imbalance of return value vs. output parameter leads to simpler solutions. Commented Aug 22 at 20:59
  • 2
    Another alternative is to return a nullable tuple, as in (Result, Parameter)?, so you return either null, or a tuple of two non-null things. Commented Aug 22 at 21:07
  • 1
    @madreflection — No. The use case is different: one output depends on another one. Actually, the existing code demonstrates clear logic. Besides, in many cases, I would replace the return with a tuple (Parameter, Result) and get rid of out. Commented Aug 22 at 21:15
  • @SergeyAKryukov If we pass bool as return with the valuetuple as out, we can check with an if statement if reading the valuetuple is even needed. Like how out int works on int.tryparse Commented Aug 23 at 4:21
  • @FSO931s — you are right, we can check whatever we need with if. I would do it, but the inquirer asks how to avoid if. I doubt it makes sense and not sure the initial requirement makes sense. Commented Aug 23 at 5:13

1 Answer 1

1

You can't express this relationship using [NotNullIfNotNull] because this attribute:

  • Does not work with out parameters (it only applies to regular parameters),

  • And you cannot reference the return value using "return" as a target (it's invalid).

[return: NotNullIfNotNull("input")]
public string? Process(string? input) => input?.ToUpper();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.