What is the difference between Convert.ToInt32 and (int)?
(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
truncatesfoo
(ifoo = Math.Floor(foo)
), whileConvert.ToInt32(foo)
uses half to even rounding (rounds x.5 to the nearest EVEN integer, meaningifoo = Math.Round(foo)
). The result is thus not just implementation-wise, but also numerically not the same.
(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.