What is the difference between Convert.ToInt32 and (int)?

To quote from this Eric Lippert article:

Cast means two contradictory things: "check to see if this object really is of this type, throw if it is not" and "this object is not of the given type; find me an equivalent value that belongs to the given type".

So what you were trying to do in 1.) is assert that yes a String is an Int. But that assertion fails since String is not an int.

The reason 2.) succeeds is because Convert.ToInt32() parses the string and returns an int. It can still fail, for example:

Convert.ToInt32("Hello");

Would result in an Argument exception.

To sum up, converting from a String to an Int is a framework concern, not something implicit in the .Net type system.


(this line relates to a question that was merged) You should never use (int)someString - that will never work (and the compiler won't let you).

However, int int.Parse(string) and bool int.TryParse(string, out int) (and their various overloads) are fair game.

Personally, I mainly only use Convert when I'm dealing with reflection, so for me the choice is Parse and TryParse. The first is when I expect the value to be a valid integer, and want it to throw an exception otherwise. The second is when I want to check if it is a valid integer - I can then decide what to do when it is/isn't.


(int)foo is simply a cast to the Int32 (int in C#) type. This is built into the CLR and requires that foo be a numeric variable (e.g. float, long, etc.) In this sense, it is very similar to a cast in C.

Convert.ToInt32 is designed to be a general conversion function. It does a good deal more than casting; namely, it can convert from any primitive type to a int (most notably, parsing a string). You can see the full list of overloads for this method here on MSDN.

And as Stefan Steiger mentions in a comment:

Also, note that on a numerical level, (int) foo truncates foo (ifoo = Math.Floor(foo)), while Convert.ToInt32(foo) uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaning ifoo = Math.Round(foo)). The result is thus not just implementation-wise, but also numerically not the same.


A string cannot be cast to an int through explicit casting. It must be converted using int.Parse.

Convert.ToInt32 basically wraps this method:

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}