Why can’t I convert object to decimal (code is below, record["Cost"] is equal 1 (int))?
I get following error
‘can not unbox record[“Cost”]’
I will use TryParse method, but I don’t understand what is source of this error.
cost = (decimal?) record["Cost"];
The value of
record["Cost"]is a boxed int. Unboxing conversions only allow you to convert to the same type. (At least broadly; there are a few differences, but they’re irrelevant here.)What you should do is unbox to
intand then convert todecimal?:Or if
costis already declared as typedecimal?, you can use the implicit conversion: