Converts and checks whether you were able to convert:
string str = '0123'; // ou qualquer coisa
int i = 0; // inicializa variável que receberá o valor inteiro
// Tenta converter str para inteiro (com saída na variável i)
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i); // Se conseguiu imprime variável
} else {
Console.WriteLine ("Erro ao converter '" + str + "' para inteiro."); // Mensagme de erro
}
or
string str = '0123'; // ou qualquer coisa
int i = 0; // inicializa variável que receberá o valor inteiro
try
{
i = Convert.ToInt32(str);
Console.WriteLine(i); // Se conseguiu imprime variável
}
catch (FormatException e)
{
Console.WriteLine("String inválida para conversão."); // Erro
}
catch (OverflowException e)
{
Console.WriteLine ("Overflow. Valor inteiro ultrapassou o limtie."); // Erro
}
Create a specific class to solve this and call a method you will trust, that is, you will invoke a method to solve this conversion and you will make sure that even if the string is invalid it will return an integer value to you.
Example, if you only need positive integer values, whenever the function returns you -1 it would be a sign that you gave error. Etc.
Code maintenance would be done and in only one location, within this method in the particular class that solves this conversion problem.
Performance is not a direct influence on both cases. If you are sure that the value is integer, not checking would gain little performance, which in my opinion is not worth, since a 'crash' in the application would be worse if your function received a string that does not contain a possible integer value.
If you have a list of strings (or
IEnumerable<string>
) to convert, could use LINQ, as I indicated in my reply. You can do it in 2 or 3 lines of code like this... depending on the code formatting you use.– Miguel Angelo