This question (or more specifically this answer) made me wonder: what statements are valid in C# as the body of a function with any return type?
So for example:
public void Foo()
{
    while (true) { }
}
public int Foo()
{
    while (true) { }
}
Both functions are valid C# functions even though the second one doesn't really return an int.
So I know that infinite loops (e.g. for(;;)) and throw new Exception() like throw statements are valid as the body of any function, but is there more statements with that property?
Update:
One more solution came to my mind, an infinite recursion:
    public string Foo()
    {
        return Foo();
    }
Interesting, one example that isn't really different than your second snippet would be:
public static int Foo()
{
    do {}
    while (true);
}
But I don't think that really counts as "different".
Also, another example of why goto is evil:
public static int Foo()
{
    start:
    goto start;
}
It's also interesting to note that this does give a compilation error:
public static int Foo()
{
    bool b = true;
    while (b) 
    {
    }
}
Even though b doesn't change. But if you explicitly make it constant:
public static int Foo()
{
    const bool b = true;
    while (b) 
    {
    }
}
It works again.
Its almost the same as the goto example but with a switch involved:
public int Foo()
{
    switch (false)
    {
         case false:
         goto case false;
    }
}
Not sure if this qualifies as a new one.
Interestingly enough, the following won't compile:
public static int Foo(bool b)
{
    switch (b)
    {
        case true:
        case false:
            goto case false;
    }
}
Evidently the compiler has no "knowledge" that a boolean can only have two possible values. You need to explicitly cover all "possible" outcomes:
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;
    }
}
Yeah...I'm bored at work today.
Non-void & no return;
public IEnumerable Foo()
{
    yield break;
}
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