Reputation: 19505
int.Parse()
and Convert.ToInt32()
?Upvotes: 593
Views: 366214
Reputation: 43
One niche but significant difference not covered in the currently accepted answer is that Entity Framework does not, at least currently, support int.Parse()
but does support Convert.Int32()
for LINQ to SQL, for some reason.
Presumably this wasn't relevant to the person that posed the question originally, considering EF had only just released back in 2008. Still, tossing that in since this does come up as a top search result and is the reason I wound up here.
Upvotes: 0
Reputation: 197
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.
Upvotes: 2
Reputation: 39
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.
Upvotes: 4
Reputation: 505
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
Upvotes: 15
Reputation: 97671
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 throw ArgumentNullException
when its argument is null the way Int32.Parse()
does. That also means that Convert.ToInt32()
is probably a wee bit slower than Int32.Parse()
, though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.
Upvotes: 524
Reputation: 618
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);
}
}
Upvotes: 51
Reputation: 33476
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
Upvotes: 98
Reputation: 501
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
Upvotes: 3
Reputation: 11489
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.
Upvotes: 11
Reputation: 61
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 )
Upvotes: 5
Reputation: 11
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();
}
}
Upvotes: 1
Reputation: 31
Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, it throws an ArgumentNullException error.
Upvotes: 2
Reputation: 132234
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.
Upvotes: 25
Reputation: 65426
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.
Upvotes: 229