Possible Duplicate:
Whats the main difference between int.Parse() and Convert.ToInt32
What is better to use int.Parse
or Convert.toInt
? which one is more error prone and performance vice good?
Possible Duplicate:
Whats the main difference between int.Parse() and Convert.ToInt32
What is better to use int.Parse
or Convert.toInt
? which one is more error prone and performance vice good?
This is the implementation of Converto.ToInt, according to Reflector :
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
The Convert.ToInt32()
underneath calls the Int32.Parse
. So the only difference is that if a null string
is passed to Convert it returns 0
, whereas Int32.Parse
throws an ArgumentNullException
.
Parse is specifically to parse strings and gives you more control over what format the string may be. Convert.ToInt will handle almost any type that can be converted in the first place. What is more error prone depends on your input and the variations you expect. int.TryParse is robust in that it won't throw an exception, the pitfall is that it is easy to hide the parsing error. This choice depends on what you want to do? Do you want to provide feedback, have detailed parsing error info, use alternative / default values?