You want to take a look at the C # language specification, chapter 7.18. It talks about constant expressions. I just summarize the basics.
The C # compiler is trying to try to evaluate the expression at compile time. As long as all operands have a known value and the operators are simple, then the compiler can calculate the value of the expression at compile time and directly use the result, rather than generate code to evaluate the expression at run time. This is similar to optimization, but it is not so, constant expressions are required in a number of places. Like the value of the case statement , declarations using the const keyword, enum declaration values, and [attribute] argument arguments.
So no problem with 10 / 0 , this is an expression with literal values ββand a simple operator so that the compiler can directly calculate the result and see that it throws an exception, so it complains about it at compile time.
d / 0 not a constant expression due to the variable d . You could argue that the compiler could know the value of d , since it got the assignment in the above expression. But this is not so; optimizing such code is the work of the jitter optimizer.
source share