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.
return
statement in the first case? Why doesn't it also require a return
statement? (What are the internals here?)return
code path will also never be reached?Don't Repeat Yourself (DRY): Using DRY or Do not Repeat Yourself principle, you make sure that you stay away from duplicate code as often as you can. Rather you replace the duplicate code with abstractions or use data normalization. To reduce duplicity in a function, one can use loops and trees.
To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.
The function UNIQUE returns the unique values contained in a column.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With