Expressions that are valid as the body of a function with any return type

This question (or more specifically this answer ) made me wonder: what statements are valid in C # as a function body with any return type?

So for example:

public void Foo() { while (true) { } } public int Foo() { while (true) { } } 

Both functions are valid C # functions, although the second does not return true int .

So, I know that infinite loops (for example, for(;;) ) and throw new Exception() , such as throw commands, are valid as the body of any function, but are there any other instructions with this property?


Update:

In my opinion, another solution appeared: infinite recursion:

  public string Foo() { return Foo(); } 
+5
source share
3 answers

Interestingly, one example that is not much different from your second snippet would be:

 public static int Foo() { do {} while (true); } 

But I do not think that this is really considered "different."

Also, another example of why goto is evil:

 public static int Foo() { start: goto start; } 

It is also interesting to note that this gives a compilation error:

 public static int Foo() { bool b = true; while (b) { } } 

Even if b does not change. But if you explicitly make it permanent:

 public static int Foo() { const bool b = true; while (b) { } } 

He is working again.

+3
source

Its almost the same as goto example, but with switch :

 public int Foo() { switch (false) { case false: goto case false; } } 

Not sure if this qualifies as new.

Interestingly, the following will not compile:

 public static int Foo(bool b) { switch (b) { case true: case false: goto case false; } } 

Obviously, the compiler does not have “knowledge” that the logical can have only two possible values. You should explicitly cover all the “possible” results:

 public static int Foo(bool b) { switch (b) { case true: case false: default: goto case true; } } 

Or in its simplest form:

 public static int Foo(bool b) { switch (b) { default: goto default; } } 

Yes ... I'm bored at work today.

+2
source

Not void and no return ;

 public IEnumerable Foo() { yield break; } 
+1
source

Source: https://habr.com/ru/post/1202883/


All Articles