Is there a way to indicate that a method will never return?

Assuming we have the following (very basic code)

public int Foo()
{
    while (true)
    {

    }
    // No "return 0" etc. needed here.
}

the compiler can understand that this method will never return, and therefore displays a warning and also it does not require the method to have a return statement.


If we have the case

public void WontExit()
{
    while (true)
    {

    }
}

public int Foo()
{
    this.WontExit();
    return default(int); // This is needed here.
}

a return statement is needed, because the compiler can seemingly not foresee that it will never be reached.


  • Why does the compiler allow for omitting the return statement in the first case? Why doesn't it also require a return statement? (What are the internals here?)
  • Is there any way to indicate the compiler (or reachability analysis) that in the second case, the return code path will also never be reached?
Jon Skeet
people
quotationmark

Why does the compiler allow for omitting the return statement in the first case?

Because the final } is unreachable. That's the condition that the compiler prevents (and that's in the specification): ever being able to reach the end of a non-void method.

Is there any way to indicate the compiler (or reachability analysis) that in the second case, the return statement will also never be reached?

No, unfortunately. There are various times that would be useful (where it would be defined as "this method can never return normally, i.e. without throwing an exception"), but there's no C# feature for it. I believe Eric Lippert blogged about this at some point... will try to find the article.

people

See more on this question at Stackoverflow