Reputation: 4359
Sometimes i wonder, when converting strings to other types, for example int32, is one way better than the other, or is it just a matter of taste?
Convert.ToInt32("123")
or
Int32.Parse("123")
or
Some other way?
Not considering the case if it's not a valid int in this question.
Upvotes: 3
Views: 7906
Reputation: 236318
Main difference between Conver.ToInt32
and Int32.Parse
is how the treat null
strings. Convert.ToInt32
returns default value in this case:
public static int ToInt32(string value)
{
if (value == null)
return 0;
return Int32.Parse(value, CultureInfo.CurrentCulture);
}
I don't like that. I think only "0"
should be parsed to 0
. This behavior initially was designed for Visual Basic programmers:
This is a set of conversion methods for programmers migrating from Visual Basic 6 to Visual Basic .NET that mirrored the behavior of the existing Visual Basic 6 conversion methods. The assumption was that C# programmers would be more comfortable with casting operators, whereas Visual Basic had traditionally used conversion methods for type conversion.
So, as non-VB programmer, I'd go with Int32.Parse
and Int32.TryParse
.
Upvotes: 2
Reputation: 31249
When converting from string to int I always use int.TryParse. Because you are not always sure you can convert a string to an int. Like this:
string temp="222";
int intValue;
if(int.TryParse(temp,out intValue))
{
//Something
}
Upvotes: 1
Reputation: 22956
The Convert.ToInt32 is actually implemented the following way...
int.Parse(value, CultureInfo.CurrentCulture);
...which is the same as your stated alternative except it takes into account the culture settings. The int.Parse method is itself implemented the following way...
Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
...where Number is an internal class that you cannot call directly. The Number.ParseInt32 method is marked with the following attribute...
[MethodImpl(MethodImplOptions.InternalCall)]
...showing that it is implemented inside the CLR itself.
Upvotes: 4
Reputation: 14929
As V4Vendetta suggested it is better to use TryParse to avoid exceptions related to converting.
int result = 0;
a = "3";
string b = "b";
string c = "2147483648"; //int32 max value + 1
int.TryParse(a, out result); // returns true result=3
int.TryParse(b, out result); // returns false result=0
int.TryParse(c, out result); // returns false result=0
Upvotes: 0