Reputation: 3450
I'm trying to better understand the compiler for C#. It insists that all code paths must return a value, and I think that's pretty fair.
It also recognizes that if an exception is thrown in a path where a value would need to be returned, that there is no point in returning something there. This also makes sense.
My question is: why wouldn't this also apply for exiting the program in a more graceful manner? e.g Environment.Exit()
-Examples-
This will compile:
private string TestMethod(int x, int y)
{
if (x == y)
{
return "this is a string";
}
throw new Exception();
// No point in a return after this, it could never be reached.
}
This will NOT compile:
private string TestMethod(int x, int y)
{
if (x == y)
{
return "this is a string";
}
Environment.Exit(1);
// This will not compile.
// "Not all code paths return a value"
// But, the code would never make it to the return here.
}
Upvotes: 3
Views: 376
Reputation: 169200
Environment.Exit
is nothing but a method as far as the compiler is concerned.
It enforces that the TestMethod
either return a value or throw an exception. Calling a method that might terminate the application or do something completely different is not a valid way to "return" from a method.
Upvotes: 7