How to parse correctly in C #


Searching for parse, I found the following:


My query is as follows:

What is the best way to parse, which is more effective and why. In which case a form is occupied, and in which case another

asked by José Miguel Sepulveda 12.04.2017 в 19:56

2 answers


I mentioned in a comment a while ago < em> "Both do the same, except that they throw different exceptions based on the value they 'parse'."

Having said that (source) , you have the following:

string convertToInt = "12";
string nullString = null;
string maxValue = "32222222222222222222222222222222222";
string formatException = "12.32";

int parseResult;

// Convertirá correctamente.
parseResult = int.Parse(convertToInt);

// Arrojará NullException.
parseResult = int.Parse(nullString); 

// Arrojará OverflowException .
parseResult = int.Parse(maxValue);

// Arrojará FormatException.
parseResult = int.Parse(formatException);

// Lo mismo, utilizando Convert.ToInt32

// Funcionará perfecto.
parseResult = Convert.ToInt32(convertToInt);

// Retornará Cero si el string es null.
parseResult = Convert.ToInt32(nullString);

// Arrojará OverflowException
parseResult = Convert.ToInt32(maxValue);

// Arrojará FormatException
parseResult = Convert.ToInt32(formatException);

You can try a Fiddle here . :)


Convert.ToInt32() has different overloads that allow you to cast virtually anything to int , however to int.Parse() you can only pass string , throwing the respective exceptions mentioned above in case case, mentioning that int.Parse() has several overloads to specify the format of the number.


In the end, very very deep, both implementations call a method called Number.Parse that is internal to the .NET Framework, see the source code of both functions below 1 :

// Int32.Parse(String s) Implementación.
public static int Parse(String s) {
    return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);

// Convert.ToInt32(String value) implementación.
public static int ToInt32(String value) {
    if (value == null)
        return 0;
    return Int32.Parse(value, CultureInfo.CurrentCulture);

What you say, at the call level, yes, Int32.Parse(string) may be faster, since you save an internal call, not as Convert.ToInt32(object) , which first evaluates the object to be converted and then calls the% method Parse() .

1 : Source code of both implementations thanks to Reference Source See: Convert.ToInt32(string) and Int32.Parse(string) .

answered by 12.04.2017 / 20:14

Both forms are valid, one the difference that I see is that the Convert.ToInt32 () allows you to assign several types of data as parameter


while Int32.Parse () can only pass a string

Int32.Parse (String)

both are valid

If you have the

Int32.TryParse ()

in case you want to validate the converison without receiving an Exception

answered by 12.04.2017 в 20:13