Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do 'Convert.ToInt32' and 'as int?' work differently?

Tags:

c#

sql

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.

like image 852
user2397578 Avatar asked Dec 07 '25 10:12

user2397578


2 Answers

Converting and casting (with the cast operator, is operator and as operator) are two different things:

  • Convert is changing one type to another type. Like from a string or Int64 to an Int32.
  • Casting can only be done from a base type to inheriting type. In this case from 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.
like image 74
Martin Mulder Avatar answered Dec 10 '25 01:12

Martin Mulder


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
like image 40
Tim S. Avatar answered Dec 10 '25 01:12

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!