Compartir a través de


Cómo: Convertir una cadena en un valor int (Guía de programación de C#)

En estos ejemplos se muestran distintas formas de convertir una cadena en un valor int. Este tipo de conversión puede resultar útil, por ejemplo, al obtener la entrada numérica de un argumento de línea de comandos. Existen métodos similares para convertir las cadenas en otros tipos numéricos, como float o long. En la siguiente tabla se muestran algunos de esos métodos.

Tipo numérico

Método

decimal

ToDecimal(String)

float

ToSingle(String)

double

ToDouble(String)

short

ToInt16(String)

long

ToInt64(String)

ushort

ToUInt16(String)

uint

ToUInt32(String)

ulong

ToUInt64(String)

Ejemplo

En este ejemplo, se llama al método ToInt32(String) para convertir una cadena de entrada en un valor int. El programa detecta las dos excepciones más comunes que este método puede producir. Si se puede incrementar el número sin que se produzca un desbordamiento de la ubicación de almacenamiento de los enteros, el programa agregará 1 al resultado e imprimirá el resultado.

int numVal = -1;
bool repeat = true;

while (repeat == true)
{
    Console.WriteLine("Enter a number between −2,147,483,648 and +2,147,483,647 (inclusive).");

    string input = Console.ReadLine();

    // ToInt32 can throw FormatException or OverflowException.
    try
    {
        numVal = Convert.ToInt32(input);
    }
    catch (FormatException e)
    {
        Console.WriteLine("Input string is not a sequence of digits.");
    }
    catch (OverflowException e)
    {
        Console.WriteLine("The number cannot fit in an Int32.");
    }
    finally
    {
        if (numVal < Int32.MaxValue)
        {
            Console.WriteLine("The new value is {0}", numVal + 1);
        }
        else
        {
            Console.WriteLine("numVal cannot be incremented beyond its current value");
        }
    }
    Console.WriteLine("Go again? Y/N");
    string go = Console.ReadLine();
    if (go == "Y" || go == "y")
    {
        repeat = true;
    }
    else
    {
        repeat = false;
    }
}
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();    

Otra forma de convertir string en int es mediante los métodos Parse o TryParse del struct System.Int32. El método ToUInt32 utiliza Parse internamente. Si el formato de la cadena no es válido, Parse produce una excepción, mientras que TryParse no produce ninguna excepción, pero devuelve false. En los siguientes ejemplos se muestran llamadas correctas e incorrectas a Parse y TryParse.

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);
// Output: -105
// TryParse returns true if the conversion succeeded
// and stores the result in the specified variable.
int j;
bool result = Int32.TryParse("-105", out j);
if (true == result)
    Console.WriteLine(j);
else
    Console.WriteLine("String could not be parsed.");
// Output: -105
try
{
    int m = Int32.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
// Output: Input string was not in a correct format.
string inputString = "abc";
int numValue;
bool parsed = Int32.TryParse(inputString, out numValue);

if (!parsed)
    Console.WriteLine("Int32.TryParse could not parse '{0}' to an int.\n", inputString);

// Output: Int32.TryParse could not parse 'abc' to an int.

Vea también

Tareas

Cómo: Determinar si una cadena representa un valor numérico (Guía de programación de C#)

Referencia

Tipos (Guía de programación de C#)