The problem is that due to casting and explicit operators:
(byte)objectExpression
is is not the same as (byte)sbyteExpression
.
The first is a [direct] cast which fails because the real object type is sbyte
and not byte
. The latter will perform a conversion that just happens to use a explicit operator (an "Explicit Conversion") with syntax that, unfortunately, still looks like a [direct] cast as per above. Here is an example of it failing sans-database:
var obj = (object)(sbyte)0;
var i1 = (int)(sbyte)obj; // okay: object (cast)-> sbyte (conversion)-> int
var i2 = (int)obj; // fail: sbyte (cast)-> int (but sbyte is not int!)
Either use an (sbyte)objectExpression
cast which is valid for the real object type, or Convert.ToInt32(objectExpression)
which takes an object
and does some magic to convert it to an int. (Using Convert.ToByte
could throw an exception on overflow.)
Happy coding!
reader["MyField"] + 0;
? – Babicheobject + int
there, for which there is no matching+
operator. – Starletint.Parse(reader["MyField"].ToString());
? – Babichebyte
,int
,double
,float
,orlong
, which can be then cast to int. The second one physically takes theToString()
of the object, which, if correctly implemented for the type of your object, should return a string of digits whichint.Parse
should be able to read as anint
. These methods require no knowledge of what the datatypes are and instead use (perhaps inefficient) type specific methods. – BabicheNullable<T>
as well. – Babiche