Convert.ToInt32(myCommand.ExecuteScalar()); // Returns 100, because myCommand is a SQL command that gets a non-null BigInt cell
myCommand.ExecuteScalar() as int? ?? 0; //Returns 0 even when myCommand is SQL command that gets a non-null BigInt cell
I have to use the second way in this case, because myCommand.ExecuteScalar() can return DBNull. But why does the second way return a different result than Convert.ToInt32?
EDIT: Thank you, all. Changed type to Int64 and it's working now.
Converting and casting (with the cast operator, is operator and as operator) are two different things:
string or Int64 to an Int32.object to Int32. The object MUST contain an Int32 to succeed. In your case it does not and the cast will return null.In code:
Int64 l = 100;
object o = l;
Int32 i1 = o as Int32? ?? 0; // Cast fails, so "as" will return 0. "??" will make it 0.
Int32 i2 = Convert.ToInt32(o); // The Int32 inside the object will be converted into an Int32 and will return 100.
Convert.ToInt32 calls the IConvertible interface on the object you pass in. For types like double and BigInteger, this is implemented and converts the object to an int as you'd expect.
The as keyword does a cast; if the cast fails, it returns null. This will only work if the object is already an int, not just if it's a type that can be converted to int. E.g.
double d = 1.0;
object o = d;
int? i1 = o as int?; // results in null
int i2 = (int)d; // works
int i3 = Convert.ToInt32(o); //works
int i4 = Convert.ToInt32(d); //works
int i5 = (int)o; // throws an exception at run time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With