C# Keywords Tutorial Part 15: checked

C# Keywords Tutorial Part 15: checked

C# is a powerful programming language that allows developers to create robust and scalable applications. One of the features that makes C# stand out is the “checked” keyword. In this blog post, we will explore what the “checked” keyword is and how it can be used in C#.

What is the “checked” keyword?

The “checked” keyword is a C# language feature that enables developers to detect and handle arithmetic overflow exceptions. Arithmetic overflow occurs when a value is too large to be stored in the data type used to represent it. For example, if we try to store a value of 256 in a byte data type, which can only hold values up to 255, an arithmetic overflow occurs.

By default, C# does not check for arithmetic overflow. Instead, it performs a wrap-around operation that discards the overflowed bits and continues with the calculation. The “checked” keyword instructs the compiler to check for overflow conditions at runtime and throw an exception if one occurs.

Using the “checked” keyword in C#

To use the “checked” keyword, we must first enable it. We can do this by either using the “#checked on” directive at the beginning of the file or by setting the “CheckForOverflowUnderflow” project property to “true.”

Once enabled, we can use the “checked” keyword in our code. The “checked” keyword can be used in two ways: as a statement or as an expression.

Using “checked” as a statement

When used as a statement, the “checked” keyword encloses a block of code that should throw an exception if an arithmetic overflow occurs. Here’s an example:

int a = int.MaxValue;
int b = 2;
int result;
 
checked
{
    result = a * b;
}
 
Console.WriteLine(result);

In this example, we are trying to multiply the maximum value of the int data type (2147483647) by 2. Since the result of this operation is too large to be stored in an int, an arithmetic overflow occurs, and an exception is thrown.

Using “checked” as an expression

When used as an expression, the “checked” keyword applies only to that expression. Here’s an example:

int a = int.MaxValue;
int b = 2;
int result = checked(a * b);
 
Console.WriteLine(result);

In this example, we are using the “checked” keyword as an expression. We are multiplying the maximum value of the int data type by 2 and storing the result in a variable called “result.” Since we are using the “checked” keyword, an exception is thrown when an arithmetic overflow occurs.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *