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();
}
}
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
intare:returnstatements in the method must return an expression convertible tointIn your example, the compiler can prove that
M2always exits by throwing, so the end of the method block is not reachable (satisfies rule #2). There are also noreturnstatements, which also satisfies rule #1. Hence this is a valid method definition.On the other hand,
M1does 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
returninstead of throwing — the compiler just tells you want you probably forgot to do.