What's the main difference between int.Parse() and Convert.ToInt32
If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use
Int32.Parse()
.If you're collecting input from a user, you'd generally use
Int32.TryParse()
, since it allows you more fine-grained control over the situation when the user enters invalid input.Convert.ToInt32()
takes an object as its argument. (See Chris S's answer for how it works)Convert.ToInt32()
also does not throwArgumentNullException
when its argument is null the wayInt32.Parse()
does. That also means thatConvert.ToInt32()
is probably a wee bit slower thanInt32.Parse()
, though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.
Better use int.Parse or Convert.ToInt32
Convert.ToInt32
is for dealing with any object that implements IConvertible
and can be converted to an int
. Also, Convert.ToInt32
returns 0
for null
, while int.Parse
throws a ArgumentNullException
.
int.Parse
is specifically for dealing with strings.
As it turns out, the string
type's IConvertible
implementation merely uses int.Parse
in its ToInt32
method.
So effectively, if you call Convert.ToIn32
on a string
, you are calling int.Parse
, just with slightly more overhead (a couple more method calls).
This is true for any conversion from string
to some primitive type (they all call Parse
). So if you're dealing with strongly-typed string
objects (e.g., you're parsing a text file), I'd recommend Parse
, simply because it's more direct.
Converting arbitrary objects (returned to you by some external library, for instance) is the scenario where I'd opt for using the Convert
class.
Any performance difference between int.Parse() and Convert.Toint()?
When passed a string as a parameter, Convert.ToInt32 calls int.Parse internally. So the only difference is an additional null check.
Here's the code from .NET Reflector
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
Int32.Parse() VS Convert.ToInt32()?
They are exactly the same, except that Convert.ToInt32(null)
returns 0
.
Convert.ToInt32
is defined as follows:
public static int ToInt32(String value) {
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
Differences between int.Parse() and ConvertTo.Int32()?
There are some differences, e.g. Convert can convert to Int32 from many objects (Int16, string, SByte, etc.). Also, Int32.Parse can accept NumberStyles, which Convert.ToInt32 cannot.
Other than that, Reflector (http://reflector.red-gate.com) has this to say:
class Convert:
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
What is the major differences between Convert.ChangeType or Convert.ToInt32?
If you know you're going to be converting a string
to Int32
, using Convert.ChangeType
seems an obscure way of doing that. I would definitely prefer either of the other calls to that.
The main difference between int.Parse
and Convert.ToInt32(x)
is that Convert.ToInt32(null)
returns 0 where as int.Parse(null)
will throw an exception. Of course, int.Parse
also gives you more control in terms of what culture is used.
I very much doubt that there's any performance benefit of one over the other: I would expect Convert.ToInt32
to call int.Parse
rather than the other way round - but it's not documented to work that way, and the hit of a single method call is unlikely to be significant. (It may well be inlined anyway.)
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.
Related Topics
When Is It Acceptable to Call Gc.Collect
Wix Installer Msi Not Installing the Winform App Created With Visual Studio 2017
How to Create Linq Expression Tree to Select an Anonymous Type
Line Delimited Json Serializing and De-Serializing
What Is the Purpose of the "Prefer 32-Bit" Setting in Visual Studio and How Does It Actually Work
Filling Missing Dates by Group
How to Convert a Structure to a Byte Array in C#
Contains()' Workaround Using Linq to Entities