s_nair
s_nair

Reputation: 812

General C# question

Following class has two method wherein M1 complain ‘not all code path return a value’ and M2 doesn’t.

Question: How does the compiler resolve M2 in context of return value ? How NotImplementedException instance is implicitly casted as int (if there is any internal compile time resolution)

class A
        {
            int M1()
            {
            }
            int M2()
            {
                throw new NotImplementedException();
            }
        }

Upvotes: 6

Views: 176

Answers (4)

Jon
Jon

Reputation: 437366

A method is not always required to return a value; in particular, it is also allowed to exit by throwing an exception (in which case no value is returned).

Edit: Specifically, the rules for the body of a method that returns int are:

  1. All return statements in the method must return an expression convertible to int
  2. The end of the method block must not be reachable

In your example, the compiler can prove that M2 always exits by throwing, so the end of the method block is not reachable (satisfies rule #2). There are also no return statements, which also satisfies rule #1. Hence this is a valid method definition.

On the other hand, M1 does not satisfy rule #2 so it is not legal.

You are probably misled by the error message which does not mention throwing at all, but consider that in almost all cases methods with return values do return instead of throwing -- the compiler just tells you want you probably forgot to do.

Upvotes: 7

javros
javros

Reputation: 823

As stated in MSDN,

The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.

When code execution run into throw statement, program is stopped and an exception message is shown to an user (if a programmer didn't specify any error handling logic)

Upvotes: 0

Bernie White
Bernie White

Reputation: 5075

The exception won't be cast as an int. The compiler knows that it is an exception that will always be reached so doesn't complain. When the exception is hit it will unwind the stack to an exception handling blocks or crash. An int will never be returned to the method caller.

Upvotes: 0

Adam Houldsworth
Adam Houldsworth

Reputation: 64477

Exceptions affect the flow of the code. Any statements after the throw would not be executed, the compiler can prove this so is happy with the path through the method.

The exception would not result in an int being returned, nothing would be returned in the normal sense. Instead an exception is generated, the CLR handles these differently.

http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx

Upvotes: 2

Related Questions