C# Checked And Unchecked

In C# programming, the checked and unchecked keywords play a vital role in managing exceptions related to integral types. These keywords define the context in which operations are performed - checked for verified context and unchecked for unverified context. The checked keyword enforces runtime validation for arithmetic overflow, while the unchecked keyword directs the compiler to disregard overflow occurrences.

C# Checked Keyword

In C# development, the checked keyword is employed to explicitly activate overflow checking for arithmetic operations and conversions involving integral types. When an overflow happens during a checked operation, the runtime will raise an OverflowException.

Syntax:

It has the following syntax.

Example

checked

{

    // Code inside here will throw an OverflowException on overflow

}

In this format, the keyword

  • checked enables overflow checking for arithmetic operations within the specified code block.
  • C# Checked Example without using the checked keyword

Let's consider an instance to demonstrate without utilizing the "check" keyword in C#.

Example

Example

using System;  

namespace CSharpProgram  

{  

    class Program  

    {  

        static void Main(string[] args)   

        {  

                int val = int.MaxValue;  

                Console.WriteLine(val + 2);  

        }  

    }  

}

Output:

Output

-2147483647

Explanation:

This instance produces an incorrect output without triggering an overflow exception.

C# Checked Example using the checked keyword

Let's consider a basic example to demonstrate the checked keyword in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int x = int.MaxValue; 

        try

        {

            // checking overflow condition

            checked

            {

                int result = x + 1;  // OverflowException

                Console.WriteLine("The Result is " + result);

            }

        }

        catch ( OverflowException m )

        {

            Console.WriteLine("Overflow detected: " + m.Message);

        }

    }

}

Output:

Output

Overflow detected: Arithmetic operation resulted in an overflow.

Explanation:

In this illustration, we showcase the process of identifying an integer overflow by employing the checked block. Initially, a variable x is set to int.MaxValue, representing the highest possible value for an integer. Within the checked block, an attempt is made to increment x by 1. As this calculation surpasses the permissible range for an integer, it results in an overflow. Subsequently, the checked block mandates the runtime to generate an OverflowException.

C# Unchecked Keyword

In C# development, the unchecked keyword is primarily used to disregard the context of overflow-checking during integral-type arithmetic operations and conversions. In case of an overflow, no exception is raised; rather, the outcome wraps around based on two's complement arithmetic.

Syntax:

It has the following syntax.

Example

unchecked

{

    // Code inside here ignores overflow, values wrap around

}

In this format,

  • unchecked is employed to deactivate overflow checking for arithmetic operations within the specified block of code.
  • C# Unchecked Keyword Example

Let's consider an example to demonstrate the unmonitored keyword in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int y = int.MaxValue;

        // This block ignores overflow

        unchecked

        {

            int result = y + 1;  // No exception, wraps around to a negative value

            Console.WriteLine("The Result is: " + result );

        }

    }

}

Output:

Output

The Result is: -2147483648

Explanation:

In this instance, a variable 'y' has been assigned int.MaxValue, representing the highest value that an int data type can store. When 1 is added to this value within the unchecked block, an overflow situation arises. Nonetheless, due to the unchecked context, the overflow doesn't trigger an exception; rather, the outcome loops back to the minimum int value.

Nested Checked and Unchecked in C#

In C#, nested checked and unchecked scopes provide the flexibility to nest one within another to manage how overflow situations are handled. The enclosing scope establishes the default overflow handling, while the enclosed scope has the ability to temporarily modify this behavior.

Syntax:

It has the following syntax.

Example

checked

{

    // Overflow checking is ON here

    // Some arithmetic operations...

    unchecked

    {

        // Overflow checking is OFF here

        // Values that overflow will wrap around silently

    }

    // Back to checked (overflow checking ON again)

}

In this particular syntax,

The

  • checked block allows for overflow checking on all arithmetic operations within the block.

Conversely, the

  • unchecked block disregards overflow checking for arithmetic operations within the block.
  • Simple Example of nested checked and unchecked

Let's consider an example to demonstrate the nested checked and unchecked keywords in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int p = int.MaxValue;

        try

        {

            checked

            {

                Console.WriteLine("Inside checked block:");

                // It will throw an OverflowException

                int res1 = p + 1;

                Console.WriteLine(" The result1 is " + res1 );

                unchecked

                {

                    // Inside unchecked

                    int res2 = p + 1;

                    Console.WriteLine(" The result2 is " + res2 );

                }

            }

        }

        catch (OverflowException m)

        {		

            Console.WriteLine("Caught overflow: " + m.Message);

        }

    }

}

Output:

Output

Inside checked block:

Caught overflow: Arithmetic operation resulted in an overflow.

Explanation:

In this instance, we showcase the application of nested verified and unverified keywords in C#. Within the verified block, the code attempts to increment int.MaxValue by 1, resulting in an Overflow, leading to the throwing of an OverflowException. The unchecked block is disregarded as the issue arises beforehand.

Difference between Checked and Unchecked keywords

There exist several key distinctions between the "checked" and "unchecked" keywords in C#. A few of these variances include:

Features Checked Unchecked
Overflow Check It throws an overflow error if the number becomes too large or too small. It ignores overflow and wraps around the value.
Use It is used when we want to catch mistakes with a very large number. It is used when we expect values to wrap around after getting too big.
Default in debug It is enabled by default to help find the error during development. It is disabled by default.
Default in Release It is disabled by default It is enabled by default.

Conclusion

In summary, C# offers the checked and unchecked keywords, which are effective tools for managing how arithmetic overflow is dealt with at runtime in a program. These keywords play a crucial role in enabling developers to control the behavior of overflow in C#.

C# checked and unchecked FAQs

1) Define the checked keyword in C#?

In C#, programmers utilize the checked keyword to specifically activate overflow checking for arithmetic operations and conversions involving integral types. When an overflow happens in a checked operation, the runtime system raises an OverflowException.

2) Define the unchecked keyword in C#?

In C# development, the unchecked keyword is primarily utilized to disregard overflow-checking context when performing arithmetic operations and conversions on integral types.

In C#, when overflow occurs in a checked block, an OverflowException is thrown to indicate that arithmetic overflow has happened during the execution of the code within the checked block. This exception helps in detecting and handling situations where calculations result in a value that exceeds the range that can be represented by the data type used. By using checked blocks, developers can ensure that overflow exceptions are caught and dealt with appropriately in their C# programs.

If an exceeding value occurs within a verified block, an OverflowException will be raised during program execution.

4) When should I use the checked keyword in C#?

In C#, the checked keyword is utilized to activate overflow checking for arithmetic operations within the block, aiding in the identification and management of overflow errors during runtime.

5) In what scenarios should the unchecked keyword be utilized in C#?

In C#, the unchecked keyword is employed to deactivate overflow checking for arithmetic operations within a specific block. This enables values to wrap around quietly instead of triggering exceptions.

Input Required

This code uses input(). Please provide values below: