Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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();
    }
like image 806
qqbenq Avatar asked Sep 18 '14 13:09

qqbenq


3 Answers

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.

like image 177
Matt Burland Avatar answered Oct 19 '22 22:10

Matt Burland


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.

like image 28
InBetween Avatar answered Oct 19 '22 22:10

InBetween


Non-void & no return;

public IEnumerable Foo()
{
    yield break;
}
like image 36
Alex K. Avatar answered Oct 20 '22 00:10

Alex K.