Search code examples
c#castingoperator-keywordoperator-precedence

Cast operation precedence in C#


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?


Solution

  • 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.