Missing return statement in a non-void method compiles

Why would a language allow us to have a non-void method having an infinite loop and not returning anything?

The rule for non-void methods is every code path that returns must return a value, and that rule is satisfied in your program: zero out of zero code paths that return do return a value. The rule is not “every non-void method must have a code path that returns”.

This enables you to write stub-methods like:

IEnumerator IEnumerable.GetEnumerator() 
{ 
    throw new NotImplementedException(); 
}

That’s a non-void method. It has to be a non-void method in order to satisfy the interface. But it seems silly to make this implementation illegal because it does not return anything.

That your method has an unreachable end point because of a goto (remember, a while(true) is just a more pleasant way to write goto) instead of a throw (which is another form of goto) is not relevant.

Why doesn’t the compiler even warn about returning something?

Because the compiler has no good evidence that the code is wrong. Someone wrote while(true) and it seems likely that the person who did that knew what they were doing.

Where can I read more about reachability analysis in C#?

See my articles on the subject, here:

ATBG: de facto and de jure reachability

And you might also consider reading the C# specification.

Leave a Comment