8

The C# compiler seems to not care if I have a throw statement after a return statement, even if the throw is quite clearly unreachable. The opposite is not true: the compiler can detect a return after a throw to be unreachable. Is this a compiler defect?

This compiles fine:

string MyProperty
{
    get
    {
        return "";
        throw new InvalidOperationException();
    }
}

string MyMethod()
{
    return "";
    throw new InvalidOperationException();
}

This will not compile, failing on the return statements:

string MyOtherProperty
{
    get
    {
        throw new InvalidOperationException();
        return "";
    }
}

string MyOtherMethod()
{
    throw new InvalidOperationException();
    return "";
}

EDIT: this is with .NET 4.5.1, C# version 5.0.

EDIT 2: This is the warning I see when compiling the second option (throw before return): Unreachable code detected

dahvyd
  • 481
  • 2
  • 7
  • 11

0 Answers0