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 areturn
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?