Yesterday Bill (boss) asked if I could help a non-.NET developer with a .NET problem they were having at another client. Of course, I said “sure”. Therein begins the saga…
David and I spent 30 minutes or so on the phone so he could explain the web app that had the issue. The error they were seeing was an Invalid Cast error on a line similar to:
decimal result = (decimal) dr[”Column1”];
Where dr is a datarow from a dataset which is of type double. Seems pretty harmless to me, but put together a sample program and run it and low and behold you get a cast error. I spent some time in the docs to see if I missed some precision issue between double and decimal but everything looked compatible to me.
Then it hit me. That line of code isn’t trying to do an explicit cast from double to decimal. It’s doing an explicit cast from object to decimal. I still didn’t think that would be an issue, but I was on the right track. After some quick googling I found a couple posts referring to the inability to cast a value type to anything other than the exact type of the object. In this case, I was breaking that rule.
No, the docs do not mention that. At least as far as I could find. Anyway, changing the above line to:
decimal result = System.Convert.ToDecimal(dr[”Column1”]);
Fixes the problem. Apparently the Convert methods have logic to handle the unboxing properly and then do the convert. Have to remember that rule. Learn something new every day!