Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 860
Jake Avatar asked Mar 29 '12 12:03

Jake


2 Answers

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.

like image 116
Dr. Wily's Apprentice Avatar answered Oct 30 '22 09:10

Dr. Wily's Apprentice


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.

like image 20
Oded Avatar answered Oct 30 '22 07:10

Oded