Reputation: 53
When I want to cast 1 to double, it does not work. When I cast 1.0 to double it works. Why?
I have the following code:
static void Main(string[] args)
{
ArrayList liste1 = new ArrayList();
liste1.Add(1);
liste1.Add("Hallo");
liste1.Add(2.5);
double num = (double)liste1[0] + (double)liste1[2];
Console.WriteLine(num);
Console.ReadLine();
}
When I change liste1.Add(1);
to liste1.Add(1.0);
it works. Why does it work with 1.0
and not with 1
?
It works too when I first cast liste1[0] to an int, and then to a double. Can you tell me why, please?
Thank you
Upvotes: 2
Views: 129
Reputation: 17274
Because if you type 1
then it will be an integer value, not a double. Integer cannot be cast to double, it can be only converted to double which is different operation even though it looks the same in code. So if you want it to be working with integer 1
, you have to cast it to int
and then convert into double
:
(double)(int)liste1[0]
Or use Convert.ToDouble
which probably does something like that inside:
((IConvertible)liste1[0]).ToDouble();
Upvotes: 1
Reputation: 1738
This is covered in detail here, on Eric Lippert's excellent blog.
In short, it's due to C#'s cast operator meaning different things in different contexts. It's best to think of int as having an implicit conversion operator allowing it to be converted to double, but if the type isn't known at compile time to be an int, this won't be run. After all, object
does not have an implicit (or explicit) conversion operator capable of converting that type, and that's what you're seemingly trying to do.
Now if desired some more work could be done behind the scenes to determine if there is a way of converting it, but as this is nontrivial it's best left to a versatile helper method like Convert.ToDouble(object)
.
Upvotes: 1
Reputation: 31
The ArrayList indexer returns an object. C# cannot cast from an object to a double. Its all to do with runtime type conversion and boxing.
This should work:
double num = (double)(int)liste1[0] +(double)liste1[2];
Upvotes: 0
Reputation: 24383
ArrayList
holds objects. If you add an int
it gets "boxed" into an object and can only be "unboxed" back to int
- not double
.
Upvotes: 4