Cast operation precedence in C#

2020-04-03 12:40发布

问题:

Will the differences below matter significantly in C#?

int a, b;
double result;
result = (double)a / b;
result = a / (double)b;
result = (double)a / (double)b;

Which one do you use?

回答1:

The cast will occur before the division.

In your examples, it doesn't matter which one you do as if one operand is a double, the runtime will cast/convert the other to a double as well.

This looks like a micro-optimization - not something worth worrying about or dealing with unless measurements show it is indeed a bottleneck.



回答2:

I do this:

result = (double)a / (double)b;

It may be strictly unnecessary, but generally I want to make sure that it will not do integer division, and I don't really care to remember the specific rules for this scenario, so it's easier (if a few more keystrokes) to be explicit.



回答3:

I do (double)a / b because I imagine an int to be something indivisible like a rock or something. When cast to a double it becomes divisible, like a cake. You can divide 3.0 cakes in four parts, but you can't divide three rocks in 4.0 parts. Or something. Do make any sense?