unchecked (Referencia de C#)unchecked (C# Reference)

La palabra clave unchecked se usa para suprimir la comprobación de desbordamiento en las operaciones y conversiones aritméticas de tipos enteros.The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.

En un contexto unchecked, si una expresión genera un valor que está fuera del intervalo del tipo de destino, no se marca el desbordamiento.In an unchecked context, if an expression produces a value that is outside the range of the destination type, the overflow is not flagged. Por ejemplo, dado que el cálculo del siguiente ejemplo se realiza en un bloque o una expresión unchecked, el hecho de que el resultado sea demasiado grande para un entero se omite y se asigna a int1 el valor -2 147 483 639.For example, because the calculation in the following example is performed in an unchecked block or expression, the fact that the result is too large for an integer is ignored, and int1 is assigned the value -2,147,483,639.

unchecked
{
    int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);

Si se quita el entorno unchecked, se produce un error de compilación.If the unchecked environment is removed, a compilation error occurs. El desbordamiento se puede detectar en tiempo de compilación porque todos los términos de la expresión son constantes.The overflow can be detected at compile time because all the terms of the expression are constants.

Las expresiones que contienen términos no constantes son unchecked de forma predeterminada en tiempo de compilación y tiempo de ejecución.Expressions that contain non-constant terms are unchecked by default at compile time and run time. Vea checked para obtener información sobre cómo habilitar un entorno checked.See checked for information about enabling a checked environment.

Puesto que la comprobación de desbordamiento lleva tiempo, el uso del código unchecked en situaciones donde no hay riesgo de desbordamiento puede mejorar el rendimiento.Because checking for overflow takes time, the use of unchecked code in situations where there is no danger of overflow might improve performance. Pero si el desbordamiento es una posibilidad, se debe usar un entorno checked.However, if overflow is a possibility, a checked environment should be used.

EjemploExample

En este ejemplo se muestra cómo usar la palabra clave unchecked.This sample shows how to use the unchecked keyword.

class UncheckedDemo
{
    static void Main(string[] args)
    {
        // int.MaxValue is 2,147,483,647.
        const int ConstantMax = int.MaxValue;
        int int1;
        int int2;
        int variableMax = 2147483647;

        // The following statements are checked by default at compile time. They do not
        // compile.
        //int1 = 2147483647 + 10;
        //int1 = ConstantMax + 10;

        // To enable the assignments to int1 to compile and run, place them inside 
        // an unchecked block or expression. The following statements compile and
        // run.
        unchecked
        {
            int1 = 2147483647 + 10;
        }
        int1 = unchecked(ConstantMax + 10);

        // The sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
        Console.WriteLine(int1);


        // The following statement is unchecked by default at compile time and run 
        // time because the expression contains the variable variableMax. It causes  
        // overflow but the overflow is not detected. The statement compiles and runs.
        int2 = variableMax + 10;

        // Again, the sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
        Console.WriteLine(int2);

        // To catch the overflow in the assignment to int2 at run time, put the
        // declaration in a checked block or expression. The following
        // statements compile but raise an overflow exception at run time.
        checked
        {
            //int2 = variableMax + 10;
        }
        //int2 = checked(variableMax + 10);

        // Unchecked sections frequently are used to break out of a checked 
        // environment in order to improve performance in a portion of code 
        // that is not expected to raise overflow exceptions.
        checked
        { 
            // Code that might cause overflow should be executed in a checked
            // environment.
            unchecked
            { 
                // This section is appropriate for code that you are confident 
                // will not result in overflow, and for which performance is 
                // a priority.
            }
            // Additional checked code here. 
        }
    }
}

Especificación del lenguaje C#C# language specification

Para obtener más información, consulte la Especificación del lenguaje C#.For more information, see the C# Language Specification. La especificación del lenguaje es la fuente definitiva de la sintaxis y el uso de C#.The language specification is the definitive source for C# syntax and usage.

Vea tambiénSee also