(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.
Each type of integer has a different range of storage capacity
Type Capacity
Int16 -- (-32,768 to +32,767)
Int32 -- (-2,147,483,648 to +2,147,483,647)
Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
As stated by James Sutherland in his answer:
int
and Int32
are indeed synonymous; int
will be a little more
familiar looking, Int32
makes the 32-bitness more explicit to those
reading your code. I would be inclined to use int where I just need
'an integer', Int32
where the size is important (cryptographic code,
structures) so future maintainers will know it's safe to enlarge an
int
if appropriate, but should take care changing Int32
variables
in the same way.
The resulting code will be identical: the difference is purely one of
readability or code appearance.
Best Answer
UInt32 does not allow for negative numbers. From MSDN:
The UInt32 value type represents unsigned integers with values ranging from 0 to 2 to the power of 32 or 2**32 (which equals to 4,294,967,295).