Reputation: 4170
I've seen the following code on the internet. Can anyone explain to me what it does? If my title is wrong, I'll change it if I get a correct answer:
public static void Calculate(float amount)
{
object amountRef = amount;
int balance = (int)(float)amountRef;
Console.WriteLine(balance);
};
What does (int)(float)
do exactly? Its difficult to find explanation on the internet.
Upvotes: 1
Views: 455
Reputation:
You're overthinking this (if you're already aware of the purpose casting serves).
A couple of extra parentheses may make it clearer:
(int)((float)amountRef)
amountRef
is cast to a float
, this new float
is then cast to an int
.
Upvotes: 3
Reputation: 98750
It is about boxing and unboxing.
If you save your float
in an object
(which is boxing), you need to unbox it with the original type first. Than your program cast it to int
.
That's why you can't say;
object amountRef = amount;
int balance = (int)amountRef;
You will get;
Specified cast is not valid. Error: Incorrect unboxing
Upvotes: 6