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

c#, type-conversion

Solution

`(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.

Problem

The following code throws an compile-time error like Cannot convert type 'string' to 'int' ``` string name = Session["name1"].ToString(); int i = (int)name; ``` whereas the code below compiles and executes successfully: ``` string name = Session["name1"].ToString(); int i = Convert.ToInt32(name); ``` I would like to know: Why does the the first code generate a compile-time error? What's the difference between the 2 code snippets?

Original source