Question

The circumstances around that brought this up are complicated but I've trimmed my problem down to it's essence. I have a byte value that is placed into double variable. Which is then stored in a object variable. When I have access to this object variable I want to cast it back to a byte. Here is a short code example of my problem:

byte originalValue = 23;
double valueAsDouble = originalValue;

// These work without issue
byte valueByte = (byte)valueAsDouble;
int valueInt = (int)valueAsDouble;
object valueObject = valueAsDouble;

// Both of these lines throw and InvalidCastException
int valueReconvertToInt = (int)valueObject;
byte valueReconvertToByte = (byte)valueObject;

My question has 2 parts I guess. Why is this not allowed? Unless I'm mistaken the object is just a wrapper around the double so shouldn't I be able to cast it the same?

My second question was going to be is there some generic work around I could use when I want to cast such a value to a byte or int (or some other datatype I could cast normally cast from a double) but I thought of a couple. Which would be best, to use Convert.ChangeType(), cast the object to a double before casting to a to the desired type, or some other solution I'm not aware of?

Was it helpful?

Solution 2

The proper workaround I think it should be to use Convert.ToByte(valueObject) to retrieve the value from type object directly as a byte. It does perform the proper casting and returns a plain byte in one step.

About why it can't a straight cast directly, I'm not really sure, but I guess it has to do with the value object being boxed when stored in an object variable, then it must be unboxed previously, and that unbox requires to be done to the same type it was originally, or a compatible one. Byte isn't compatible with double (as it has a wider range), so you can only unbox to a double (since the value is really a double), and then cast that double to a byte. The Convert Class seems to do all that internally.

The unboxing reference is here: http://msdn.microsoft.com/library/b95fkada(v=vs.80).aspx

OTHER TIPS

Simply because it isn't a byte. It's a double. Extract the double, then cast it to byte as before:

byte valueReconvertToByte = (byte)((double)valueObject);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top