If we try to run this code:
int d = 10/0;
We get a compiler error. So we cannot divide by zero.
Now consider this code:
<
You'll want to take a look at the C# Language Specification, chapter 7.18. It talks about constant expressions. I'll just summarize the basics.
The C# compiler makes an effort to try to evaluate an expression at compile time. As long as the operands all have a known value and the operators are simple ones then the compiler can compute the value of the expression at compile time and use the result directly, instead of generating the code to evaluate the expression at runtime. This sounds like an optimization, but it is not quite like that, constant expressions are required in a number of places. Like the value of a case statement, declarations that use the const keyword, the values of an enum declaration and the arguments of an [attribute].
So no trouble with 10 / 0
, that's an expression with literal values and a simple operator so the compiler can directly compute the result and see that it will trigger an exception so complains about it at compile time.
The d / 0
is not a constant expression because of the d
variable. You could argue that the compiler could well know the value of d
since it got assigned in the statement above it. But it doesn't do this, optimizing such code is the job of the jitter optimizer.