c# - PropertyInfo.GetValue returns int, but casting to decimal results in InvalidCastException -


we have following code produces unexpected result (probably because don't understand fundamental that's going on here).

var propinfo = propobj.gettype().getproperty(prop.propertyname); var valueobj = propinfo.getvalue(obj); /* valueobj contains number 0*/  var valuedecimal = (decimal) valueobj; /* produces invalidcastexception 

can explain going on here , how fix code? in case want decimal value, if 0.

you need first unbox int , can convert decimal

var propinfo = propobj.gettype().getproperty(prop.propertyname); var valueint = (int)propinfo.getvalue(obj); /* valueobj contains number 0*/  var valuedecimal = (decimal) valueint;  

although syntax same conversion between object , int unboxing operation, if try convert object decimal tries unbox decimal , fails.

internals

if in generated il version in question , version above, can more see difference:

for original cast decimal generates:

unbox.any [mscorlib]system.decimal 

for version above:

call valuetype [mscorlib]system.decimal [mscorlib]system.decimal::op_implicit(int32) 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -