1

Conversion #1:

int result = (int)command.ExecuteScalar();

Conversion #2:

int result = Convert.ToInt32(command.ExecuteScalar());

I want to know their specific use, thanks!

  • 1
    You might find your answer here : http://stackoverflow.com/questions/15394032/difference-between-casting-and-using-the-convert-to-method – Kavindu Dodanduwa Mar 11 '15 at 02:08

1 Answers1

1

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.

tophallen
  • 1,033
  • 7
  • 12