Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?
like image 967
Thomas Flinkow Avatar asked Feb 26 '18 16:02

Thomas Flinkow


People also ask

How can programmers avoid duplicating code?

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.

How do you prevent duplicates in Java?

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.

Which function will ignore duplicate values?

The function UNIQUE returns the unique values contained in a column.


1 Answers

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.

like image 65
Jon Skeet Avatar answered Sep 27 '22 23:09

Jon Skeet