This is caused by the use of CLR boxing and unboxing . Whenever you consider a value type as an object, the CLR automatically binds this value type to you inside the object. However, the CLR only supports unpacking objects in a box into their original value type on MSDN :
Unpacking
Unboxing is an explicit conversion from a type object to a type value, or from an interface type to a value type that implements an interface. The unboxing operation consists of:
object o = b; Causes the CLR to create a byte in bytes and stores it in o as an object. var i = (int)o; then tries to unpack the byte byte into int. This throws an exception because the type of box (byte) and value type (int) are different.
source share