Using C# 8+ with nullable context enabled, I have a method which returns
- An enum representing various error codes, or success;
- An object (if success) or null (if error)
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.