Thursday, August 21, 2008

Unable to cast object of type 'System.Int32' to type 'System.String'

Came across an interesting situation today with the error message:  System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'

I couldn't work out how you couldn't cast an Int32 to a string? Seems impossible doesn't it?

Try this little snippet of code and you will be able to get that error:

            Hashtable groupList = new Hashtable();
            groupList.Add(11, new object());
            groupList.Add("12", new object());
            List<int> groups = groupList.Keys.Cast<string>().Select(a => Convert.ToInt32(a)).ToList();

The Hashtable accepts a string as a key in the second Add() call so it now has both int's and strings as keys. What I'm guessing though is that on a call to Add() the Hastable checks what data type for the key is. On the first call this data type is unset so it takes the data type of the first param and uses that as the data type for the key. On subsequent calls to Add() it sees that the data type for the key is set so just adds the item as an object for the key. This is just my guess and I'm sure if I took the time to look at this member function in Reflector I'd find out if I'm right or not.

No comments:

Post a Comment