So in C# whenever I retrieved a tinyint from my MSSQL database I used the following cast.
(int)(byte)reader["MyField"];
However, that cast doesn't seem to work in MySQL.
What I have tried
(byte)reader["MyField"];
and just
(int)reader["MyField"];
Edit 1
Exception
The specified cast is not valid.
Edit 2
This is the data type.
{Name = "SByte" FullName = "System.SByte"}
To determine the proper type, look at the value of
reader["MyField"].GetType()
in the debugger.
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!
May I suggest to let the system work against itself? The DataReader class provides features for getting the correct type of value:
reader.GetInt32("id");
reader.GetByte("MyByteField");
This way the Reader provides you with the type you expect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.