- What is the main difference between
int.Parse()
andConvert.ToInt32()
? - Which one is to be preferred
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.
-
54As others point out, Convert.ToInt32(s) doesn't throw an exception when s is null, but Parse() does. "A bit slower" is completely beside the point as you'll never measure the difference. – Robert Paulson Oct 14 '08 at 1:04
-
4Thanks, Robert! I'm editing my answer for some more completeness. But as far as performance goes, I'll bet the difference in speed would be detectable if you're calling it in a nested loop... – Dave Markle Oct 14 '08 at 13:01
-
5Actually, since the
ToInt32
method has an overload for loads of types, there among themSystem.String
, no time will be lost discerning the type. The actual code does nothing but return 0 for null values, andint.Parse(value, CultureInfo.CurrentCulture)
for everything else. – Andreas Eriksson Dec 20 '12 at 9:42 -
6@StealthRabbi: In the "Return value" section of the documentation: "A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null." – Dave Markle Dec 16 '13 at 20:11
-
3please remove your mention of
Int32.TryParse()
inConvert.ToInt32()
because it is incorrect. Convert throws an exception if the string is formatted incorrectly. – Dehalion Jun 3 '14 at 11:03
Have a look in reflector:
int.Parse("32"):
public static int Parse(string s)
{
return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
which is a call to:
internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
Convert.ToInt32("32"):
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
As the first (Dave M's) comment says.
-
21
-
1
-
2In short,
Convert.ToInt32
returns0
ifnull
to preventint.Parse
from raising anArgumentNullException
. – André Leria Oct 8 '13 at 13:27 -
4@SkorunkaFrantišek - The expression
default(int)
is evaluated at compile time, since its an intrinsic value - the result of the expression is0
, so the compiler inserts a literal0
. The IL disassembly tools can't know any better, so they just show you a literal zero. – antiduh Jan 13 '14 at 20:18 -
4@SkorunkaFrantišek This is entirely besides the point. The user was copying reflected code. To change it would be an incorrect representation of what is compiled. If the user had original source and the original source had default(int) then that is what the user would have posted. – rshadman Aug 14 '15 at 14:30
No difference as such.
Convert.ToInt32()
calls int.Parse()
internally
Except for one thing Convert.ToInt32()
returns 0
when argument is null
Otherwise both work the same way
-
5More precisely,
Convert.ToInt32(string)
callsint.Parse
internally.Convert.ToInt32(object)
, however, calls((IConvertible) value).ToInt32
, which in the case ofstring
callsConvert.ToInt32(string)
... a bit convoluted... – Timwi May 24 '11 at 19:18 -
3Yeah, Convert.ToInt32(char) will actually return (int)value, which will turn '1' into 49. Not generally the intended functionality. – Dale K Oct 24 '13 at 18:28
int.Parse(string s)
- Integer in RANGE > returns integer value
- Null value > ArguementNullException
- Not in format > FormatException
- Value not in RANGE > OverflowException
Convert.ToInt32(string s)
- Integer in RANGE > returns integer value
- Null value > returns "0"
- Not in format > FormatException
- Value not in RANGE > OverflowException
bool isParsed = int.TryParse(string s,out res)
- Integer in RANGE > returns integer value, isParsed = true
- Null value > returns "0", isParsed = false
- Not in format > returns "0", isParsed = false
- Value not in RANGE > returns "0", isParsed = false
Try this code below.....
class Program
{
static void Main(string[] args)
{
string strInt = "24532";
string strNull = null;
string strWrongFrmt = "5.87";
string strAboveRange = "98765432123456";
int res;
try
{
// int.Parse() - TEST
res = int.Parse(strInt); // res = 24532
res = int.Parse(strNull); // System.ArgumentNullException
res = int.Parse(strWrongFrmt); // System.FormatException
res = int.Parse(strAboveRange); // System.OverflowException
// Convert.ToInt32(string s) - TEST
res = Convert.ToInt32(strInt); // res = 24532
res = Convert.ToInt32(strNull); // res = 0
res = Convert.ToInt32(strWrongFrmt); // System.FormatException
res = Convert.ToInt32(strAboveRange); //System.OverflowException
// int.TryParse(string s, out res) - Test
bool isParsed;
isParsed = int.TryParse(strInt, out res); // isParsed = true, res = 24532
isParsed = int.TryParse(strNull, out res); // isParsed = false, res = 0
isParsed = int.TryParse(strWrongFrmt, out res); // isParsed = false, res = 0
isParsed = int.TryParse(strAboveRange, out res); // isParsed = false, res = 0
}
catch(Exception e)
{
Console.WriteLine("Check this.\n" + e.Message);
}
}
The difference is this:
Int32.Parse()
and Int32.TryParse()
can only convert strings. Convert.ToInt32()
can take any class that implements IConvertible
. If you pass it a string, then they are equivalent, except that you get extra overhead for type comparisons, etc. If you are converting strings, then TryParse()
is probably the better option.
Int32.parse(string)--->
Int32.Parse (string s) method converts the string representation of a number to its 32-bit signed integer equivalent. When s is a null reference, it will throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException. For example:
string s1 = "1234";
string s2 = "1234.65";
string s3 = null;
string s4 = "123456789123456789123456789123456789123456789";
result = Int32.Parse(s1); //1234
result = Int32.Parse(s2); //FormatException
result = Int32.Parse(s3); //ArgumentNullException
result = Int32.Parse(s4); //OverflowException
Convert.ToInt32(string) --> Convert.ToInt32(string s) method converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method. When s is a null reference, it will return 0 rather than throw ArgumentNullException. If s is other than integer value, it will throw FormatException. When s represents a number less than MinValue or greater than MaxValue, it will throw OverflowException.
For example:
result = Convert.ToInt32(s1); // 1234
result = Convert.ToInt32(s2); // FormatException
result = Convert.ToInt32(s3); // 0
result = Convert.ToInt32(s4); // OverflowException
-
1
TryParse is faster...
The first of these functions, Parse, is one that should be familiar to any .Net developer. This function will take a string and attempt to extract an integer out of it and then return the integer. If it runs into something that it can’t parse then it throws a FormatException or if the number is too large an OverflowException. Also, it can throw an ArgumentException if you pass it a null value.
TryParse is a new addition to the new .Net 2.0 framework that addresses some issues with the original Parse function. The main difference is that exception handling is very slow, so if TryParse is unable to parse the string it does not throw an exception like Parse does. Instead, it returns a Boolean indicating if it was able to successfully parse a number. So you have to pass into TryParse both the string to be parsed and an Int32 out parameter to fill in. We will use the profiler to examine the speed difference between TryParse and Parse in both cases where the string can be correctly parsed and in cases where the string cannot be correctly parsed.
The Convert class contains a series of functions to convert one base class into another. I believe that Convert.ToInt32(string) just checks for a null string (if the string is null it returns zero unlike the Parse) then just calls Int32.Parse(string). I’ll use the profiler to confirm this and to see if using Convert as opposed to Parse has any real effect on performance.
Hope this helps.
-
3When you look at the source from TryParse it actually has no exception handling at all - just character manipulation and bit shifting, thanks for the link – Chris S Oct 14 '08 at 14:55
-
2According to these benchmarks, Parse, TryParse, and Convert are pretty much the same speed unless you're converting more than 2 million objects. – Free Coder 24 Jan 9 '15 at 0:18
Convert.ToInt32
has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.
It will attempt to convert from the following TYPES;
Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date
and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider
Parse on the other hand only has 4 overloads or 4 different ways you can call the method.
Integer.Parse( s As String)
Integer.Parse( s As String, style As System.Globalization.NumberStyles )
Integer.Parse( s As String, provider As System.IFormatProvider )
Integer.Parse( s As String, style As System.Globalization.NumberStyles, provider As System.IFormatProvider )
Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, it throws an ArgumentNullException error.
It depends on the parameter type. For example, I just discovered today that it will convert a char directly to int using its ASCII value. Not exactly the functionality I intended...
YOU HAVE BEEN WARNED!
public static int ToInt32(char value)
{
return (int)value;
}
Convert.ToInt32('1'); // Returns 49
int.Parse('1'); // Returns 1
-
Can
char
convert implicitly tostring
in C#? It certainly can in VB.NET, and so programmers in that language would likely expectConvert.ToInt32("1"c)
andConvert.ToInt32("1")
to be equivalent, but I don't think C# has that implicit conversion. – supercat Oct 29 '13 at 15:46 -
You cannot convert char to string, either implicitly or explicitly. You would need to call '1'.ToString() or new string('1', 1); – Dale K Nov 4 '13 at 20:01
-
3I wouldn't consider the "warning" terribly significant for C#, since that language regards
char
values as being a bit more number-ish than vb.net. The danger would be greater in vb.net, where there because of an implicit cast there's less of a perceived difference betweenChar
andString
. – supercat Nov 5 '13 at 1:30
Here is a detail for int.Parse
and Convert.ToInt32
:
Say, you have a char array, char[] a=['1','2','3','4']
and want to convert each element into an integer.
The Convert.ToInt32(a[0])
will give you a number of 49. It treats it as ASCII code
The int.Parse(a[0])
will give you the right output which is 1
If you have a string array string[] b=['1','2','3','4']
, then Convert.ToInt32
and int.Parse
will have no difference in output. Both return the right integer.
for clarification open console application, just copy below code and paste it in static void Main(string[] args)
method, I hope you can understand
public class Program
{
static void Main(string[] args)
{
int result;
bool status;
string s1 = "12345";
Console.WriteLine("input1:12345");
string s2 = "1234.45";
Console.WriteLine("input2:1234.45");
string s3 = null;
Console.WriteLine("input3:null");
string s4 = "1234567899012345677890123456789012345667890";
Console.WriteLine("input4:1234567899012345677890123456789012345667890");
string s5 = string.Empty;
Console.WriteLine("input5:String.Empty");
Console.WriteLine();
Console.WriteLine("--------Int.Parse Methods Outputs-------------");
try
{
result = int.Parse(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:"+ee.Message);
}
try
{
result = int.Parse(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = int.Parse(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = int.Parse(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = int.Parse(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------Convert.To.Int32 Method Outputs-------------");
try
{
result= Convert.ToInt32(s1);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
result = Convert.ToInt32(s2);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
result = Convert.ToInt32(s3);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
result = Convert.ToInt32(s4);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
result = Convert.ToInt32(s5);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.WriteLine();
Console.WriteLine("--------TryParse Methods Outputs-------------");
try
{
status = int.TryParse(s1, out result);
Console.WriteLine("OutPut1:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut1:" + ee.Message);
}
try
{
status = int.TryParse(s2, out result);
Console.WriteLine("OutPut2:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut2:" + ee.Message);
}
try
{
status = int.TryParse(s3, out result);
Console.WriteLine("OutPut3:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut3:" + ee.Message);
}
try
{
status = int.TryParse(s4, out result);
Console.WriteLine("OutPut4:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut4:" + ee.Message);
}
try
{
status = int.TryParse(s5, out result);
Console.WriteLine("OutPut5:" + result);
}
catch (Exception ee)
{
Console.WriteLine("OutPut5:" + ee.Message);
}
Console.Read();
}
}
Parse() methods provide the number styles which cannot be used for Convert(). For example:
int i;
bool b = int.TryParse( "123-",
System.Globalization.NumberStyles.AllowTrailingSign,
System.Globalization.CultureInfo.InvariantCulture,
out i);
would parse the numbers with trailing sign so that i == -123
The trailing sign is popular in ERP systems.