Using C# 8+ with nullable context enabled, I have a method which returns
as a ValueTuple. Aside from the null-forgiving operator, is there a way I can tell the compiler that the object is not null if the enum value indicates success?
private (EnumResult, SomeClass?) DoThing(...)
{
if (...)
return (EnumResult.Error1, null);
if (...)
return (EnumResult.Error2, null);
return (EnumResult.Success, new SomeClass(...));
}
(EnumResult result, SomeClass? someClass) = DoThing(...);
if (result == EnumResult.Success)
{
// `someClass` should not be null here, but the compiler doesn't know that.
}
I am aware there are nullable static analysis attributes which can be applied when using a bool return and an out parameter:
private bool TryDoThing(..., [NotNullWhen(true)] out SomeClass? someClass)
{
if (...)
{
someClass = null;
return false;
}
someClass = new SomeClass(...);
return true;
}
if (TryDoThing(..., out SomeClass someClass))
{
// The compiler knows that `someClass` is not null here.
}
But I couldn't determine how to apply something similar when returning a ValueTuple.
I am using an enum rather than a bool or throwing exceptions because the result code is communicated across a named pipe, where the process on the other side parses it back into an enum and then reacts according to the specific error. I am using a ValueTuple rather than an out parameter out of personal preference.
No. At this time, the MaybeNullWhen/NotNullWhen attributes only work to signal that the null state of an out parameter depends on a bool return value.
There is currently no plan to allow the null state of a variable to depend on the value of an enum return value, for example.
There is also no plan to allow an interdependence between the elements of a tuple return value, i.e. the (object? result, bool ok) Method() pattern. If you are interested in such functionality getting added to the language, feel free to start a discussion on how it would work at https://github.com/dotnet/csharplang/discussions.