Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
            }
        }
like image 299
s_nair Avatar asked Sep 13 '11 10:09

s_nair


2 Answers

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.

like image 170
Jon Avatar answered Sep 18 '22 23:09

Jon


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

like image 24
Adam Houldsworth Avatar answered Sep 17 '22 23:09

Adam Houldsworth