Mike Turner Mike Turner - 1 year ago 98
JSON Question

Converting data from wcf using reflection Object of type 'System.Int64' cannot be converted to type 'System.Int32'

I'm retrieving a datatable from a wcf function WebMessageFormat = Json and then setting the properties of my data contract using reflection. I'm getting the following error on an int field -


Object of type 'System.Int64' cannot be converted to type 'System.Int32


Can somebody explain what this is and how to address?

Answer Source

When casting boxed value-type values, you must cast to the correct type. For example:

var myLong = (object)42L;

var intValue = (int)myLong; // WRONG - myLong is a boxed long, not int
var intValue2 = (int)(long)myLong; // CORRECT - myLong is unboxed first, then converted

Note that you may get an OverflowException if int isn't big enough to contain your long value even when you unbox the value correctly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download