Given following code:
object value = header.DataContentType switch
{
DataContentType.DOUBLE => (double)BitConverter.ToDouble(currentValueBytes.ToArray()),
DataContentType.FLOAT => (float)BitConverter.ToSingle(currentValueBytes.ToArray()),
DataContentType.BYTE => (byte)contentData[i],
DataContentType.SHORT => (short)BitConverter.ToInt16(currentValueBytes.ToArray()),
DataContentType.INTEGER => (int)BitConverter.ToInt32(currentValueBytes.ToArray()),
DataContentType.LONG => (long)BitConverter.ToInt64(currentValueBytes.ToArray()),
_ => throw new InvalidDataException("Invalid data type"),
};
Now, in case when header.DataContentType is DataContentType.INTEGER, the value gets assigned as a double to value instead of as an int and (int)value causes an InvalidCastException
If I debug I can clearly see that it steps into the INTEGER case, and if I evaluate BitConverter.ToInt32(currentValueBytes.ToArray()) in the debug console I get an integer returned. However, as soon as the switch case is exited the variable value is of type double.
Further, if I manually do value = BitConverter.ToInt32(currentValueBytes.ToArray()) the variable is of the correct type int. Implying the switch statement has to change the type to double for some weird reason.
I would like the switch case to return whatever type the BitConverter returns. How can I make the BitConverter return the type of the correct BitConverter case?