'Is not' operator with custom 'throw exception' helper method makes variable unnasigned

76 Views Asked by At

Let's say we have a code like this:

if (obj is not IFoo foo)
{
    throw new ArgumentException("Can't do that!");         
}
foo.Foo();

Works as expected: foo is not assigned in the if context, but is assigned after.

But, if I want to make a throw helper for inlining and readability purposes - it stops working.

if (obj is not IFoo foo)
{
    ThrowHelper.ThrowArgumentException("Can't do that!");         
}
foo.Foo(); // CS0165

I can see why, the compiler doesn't know that ThrowHelper methods throw exceptions, so it thinks we can get further to foo, which the is not pattern does not allow.

Question: is there any way out of this situation? I understand, that i can invert the if, but i'm curious: can i "mark" ThrowHelper methods so the compiler knows that it always throws an exception?

1

There are 1 best solutions below

8
Gerry Schmitz On

foo.Foo() is the problem ... "foo" is scoped (and "not" scoped) to the "if block" (via "is" and "not"); foo.Foo() is "outside" of that scope.