32

I have code as follows:

Dictionary<object, object> dict = ...
Color = (int)dict.GetValue("color");

When I convert the Color to an int, I get the following exception:

System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.Int32'.

I am not sure why I can't just cast from a long to an int. I know for a fact that the value is less than 0xFFFFFF (24 bits) since it is a color.

I tried using unchecked but that didn't help either.

Kostub Deshmukh
  • 2,852
  • 2
  • 25
  • 35
  • Error is what error is, although it is a bit confusing because `(x)expr` is either a *cast* or a *conversion* depending on the expression type. The correction would be `(int)(long)dict.GetValue("color")` which corresponds to `(conversion)((cast)obj)`. – user2864740 Jul 31 '15 at 04:15

2 Answers2

60

You must first unbox the value as the dictionary's value type is object.

Dictionary<object, object> dict = ...
Color = (int)(long)dict.GetValue("color");
Matthew
  • 24,703
  • 9
  • 76
  • 110
17

If you don't know the original type, the following idiom may be more convenient.

public T Get<T>(string key)
{
    return (T) Convert.ChangeType(_dict[key], typeof(T), CultureInfo.InvariantCulture);
}
Ryo Asai
  • 1,088
  • 1
  • 6
  • 14