Conversion #1:
int result = (int)command.ExecuteScalar();
Conversion #2:
int result = Convert.ToInt32(command.ExecuteScalar());
I want to know their specific use, thanks!
Conversion #1:
int result = (int)command.ExecuteScalar();
Conversion #2:
int result = Convert.ToInt32(command.ExecuteScalar());
I want to know their specific use, thanks!
These are two very similar operations - but with different results (in some cases).
(int)
is a Casting Operator. Operators are used for various things, such as Addition, Subtraction, and Bitwise operations. A conversion operator is used to implicitly(implicit), or explicitly(explicit) convert one type to another. This is an example of what the operator looks like in C# code for going from object to int:
public static explicit operator Int32(object obj)
{
return ((IConvertible)obj).ToInt32();
}
Using the Convert
class does the same thing, but more explicitly, and sometimes types will have a more specific type in their class that the operator will use instead of the Convert
class. But more often than not, they are actually calling the same thing. See Decimal for an example of it's ToInt32()
method.
The Convert class method (From .NET source):
public static int ToInt32(object value) {
return value == null? 0: ((IConvertible)value).ToInt32(null);
}
So in general, you can go either way. And since you are just dealing with an unboxing operation (from object
to a struct), you won't have to worry too much if you know the type. -
However, note that if you pass a null object, it won't throw when you use Convert.ToInt32(object obj)
because it will return 0. This can be very useful.