How to get tinyint data type from MySQL in C #?

So, in C # whenever I returned tinyint from my MSSQL database, I used the following listing.

(int)(byte)reader["MyField"]; 

However, this application does not work in MySQL.

What i tried

 (byte)reader["MyField"]; 

and just

 (int)reader["MyField"]; 

Change 1

Exception

 The specified cast is not valid. 

Edit 2

This is a data type.

 {Name = "SByte" FullName = "System.SByte"} 
+8
c # mysql tinyint
source share
2 answers

The problem is that due to castings and explicit operators:

(byte)objectExpression is not the same as (byte)sbyteExpression .

The first is [direct], which is not executed, because the real type of object is sbyte , not byte . The latter will perform a conversion that simply uses an explicit operator ("Explicit conversion") with syntax, which, unfortunately, still looks like [direct], as indicated above. The following is an example of a failed 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!) 

Use either the (sbyte)objectExpression cast, which is valid for the real type of the object, or Convert.ToInt32(objectExpression) , which takes the object and does some magic to convert it to int. (Using Convert.ToByte can throw an overflow exception.)

Happy coding!

+8
source share

Review the value to determine the correct type.

 reader["MyField"].GetType() 

in the debugger.

+9
source share

All Articles