No C#, existem duas formas (dentre outras) de se converter outros tipos para int
:
Convert.ToInt32(valor)
e Int32.Parse(valor)
.
Qual a principal diferença entre essas duas formas de conversão?
Stack Overflow em Português é um site de perguntas e respostas para programadores profissionais e entusiastas. Leva apenas um minuto para se inscrever.
Inscreva-se para participar desta comunidadeO Int32.Parse(valor)
só converte conteúdo vindo de string. O Convert.ToInt32()
tem sobrecargas para trabalhar com vários tipos. Esta é a principal diferença.
Mas a melhor forma é ver como ele é internamente:
Parse()
:
public static int Parse(string s)
{
return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
Convert()
:
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
Coloquei no GitHub para referência futura.
Retirado dessa resposta do SO.
Mas você pode ver o código fonte real: Convert.ToInt32()
e Parse()
. Melhor ainda acompanhar no .NET Core (Convert.ToInt32()
e Parse()
).
Prefira o TryParse()
Relacionada: Qual a diferença entre usar (int)variavel ou Convert.ToInt32(variavel)?.
Não deixe de ver: Diferenças entre Parse() vs TryParse().
Jogando Int32.Parse()
no Reflector:
public static int Parse(string s)
{
return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
Que por sua vez, chama:
internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
byte* stackBuffer = stackalloc byte[1 * 0x72];
NumberBuffer number = new NumberBuffer(stackBuffer);
int num = 0;
StringToNumber(s, style, ref number, info, false);
if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
{
if (!HexNumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
if (!NumberToInt32(ref number, ref num))
{
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}
return num;
}
Jogando Convert.ToInt32()
no Reflector:
public static int ToInt32(string value)
{
if (value == null)
{
return 0;
}
return int.Parse(value, CultureInfo.CurrentCulture);
}
Int32.Parse()
é visivelmente mais rápido que Convert.ToInt32()
, mas mais insegura. Você deve usar Int32.Parse()
quando tem certeza que o valor de entrada é um inteiro;Int32.TryParse()
, que é um pouco mais segura. Devolve zero se a conversão falhar e não lança exceção;Convert.ToInt32()
é um envelope um pouco mais seguro de Int32.Parse()
(dá pra ver pelo código.Ainda, a maneira mais rápida de realizar a conversão é por um simples cast:
var inteiro = (int)meuObjeto;
Claro que é bastante inseguro fazer isso, mas compensa se, novamente, você sabe que o que tem dentro do object
é um inteiro.
Por esta resposta, é possível ver o assembly deste cast:
.locals init (
[0] object x,
[1] int32 Y)
L_0000: ldc.i4.1
L_0001: box int32
L_0006: stloc.0
L_0007: ldloc.0
L_0008: unbox int32
L_000d: ldobj int32
L_0012: stloc.1
L_0013: ret
Enquanto que Convert.ToInt32()
gera:
.locals init (
[0] object x,
[1] int32 Y)
L_0000: ldc.i4.1
L_0001: box int32
L_0006: stloc.0
L_0007: ldloc.0
L_0008: call object [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::GetObjectValue(object)
L_000d: call int32 [mscorlib]System.Convert::ToInt32(object)
L_0012: stloc.1
L_0013: ret
Esta resposta tem um benchmark completo sobre todos os modos de atribuição possíveis para um inteiro. A diferença é estrondosa.
Convert
de numérico com Parse
de string . São duas entradas distintas. É como dizer que uma Ferrari é mais rápida que o caminhão, mas estamos querendo saber qual carrega mais carga.