I am wondering if the following expressions are equivalent (In C#):
float x = ... ;
int y = ... ;
var result = (float) (x / y);
Versus:
var result = x / (float)y;
Where can i read more about this specific topic?
What i am interested in is:
- Will these always produce the same result?
- Does one option perform more efficiently than the other?
Yes, they will behave the same way. In fact, you can just use:
or
Section 7.8.2 of the C# 4 spec shows which division operators are avaiable – and there’s no
float operator /(float, int)operator. Instead, the C# compiler uses the implicit conversion frominttofloat, and uses thefloat operator /(float, float)operator.This is just normal operator overload resolution (spec section 7.3.4) and implicit numeric conversions (spec section 6.1.2).
When in doubt consult the spec. I have a web page with links to the different versions; the C# 5 spec is bundled with VS 2012 but there’s no separate download for it right now.