I have a method that returns a tuple (MyEnum, MyObject?)
. There is one and only one enum value that means MyObject
is not null - all the others mean MyObject
will be null (and the string
will have a message).
Something along the lines of
(MyEnum response, Package? package) MyMethod()
{
if (Today == NiceDay)
{
return (MyEnum.Happy, new Package("I'm happy!"));
}
if (Today == RainyDay)
{
return (MyEnum.Pensive, null);
}
if (Today == SnowyDay)
{
return (MyEnum.Cold, null);
}
}
Obviously, if I try and use MyMethod().package.message
, the compiler will warn me about the possibility of a null reference. I'm aware of the null-forgiving operator, but that kind of feels like a quick-fix.
Is there a way to "tell" the compiler to expect a value when MyMethod().response
is MyEnum.Happy
, and null
when it is any other value, or is the null-forgiving operator the correct and expected way to deal with this situation?