Converts and verifies whether or not 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, ie you will invoke a method to resolve this conversion and 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 signal that it gave error. Etc.
The maintenance of the code would be done in one place, within that method in the particular class that solves this conversion problem.
Performance is not directly influenced in either case. 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 did not contain a possible integer value.