Introduction
In C#, the checked
and unchecked
keywords are used to control the behavior of overflow-checking for integral-type arithmetic operations and conversions. By default, arithmetic operations and conversions in C# do not check for overflow unless specified otherwise. The checked
keyword ensures that an overflow will raise an exception, while the unchecked
keyword suppresses overflow-checking and allows the overflow to occur without throwing an exception.
Overflow and Underflow
Overflow
Overflow occurs when a value is assigned to a variable that exceeds the maximum value the variable can hold. For example, assigning a value greater than int.MaxValue
to an int
variable.
Underflow
Underflow occurs when a value is assigned to a variable that is less than the minimum value the variable can hold. For example, assigning a value less than int.MinValue
to an int
variable.
Using checked
The checked
keyword ensures that an exception is thrown if an overflow occurs during an arithmetic operation or conversion.
Syntax
checked
{
// Code block with overflow checking enabled
}
Example: Using checked
Block
using System;
namespace CheckedExample
{
class Program
{
static void Main(string[] args)
{
try
{
int max = int.MaxValue;
Console.WriteLine($"Max Value: {max}");
// This will throw an OverflowException
int result = checked(max + 1);
Console.WriteLine($"Result: {result}");
}
catch (OverflowException ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}
}
}
}
Output
Max Value: 2147483647
Exception caught: Arithmetic operation resulted in an overflow.
Example: Using checked
Statement
using System;
namespace CheckedExample
{
class Program
{
static void Main(string[] args)
{
try
{
int max = int.MaxValue;
Console.WriteLine($"Max Value: {max}");
// This will throw an OverflowException
int result;
checked
{
result = max + 1;
}
Console.WriteLine($"Result: {result}");
}
catch (OverflowException ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}
}
}
}
Output
Max Value: 2147483647
Exception caught: Arithmetic operation resulted in an overflow.
Using unchecked
The unchecked
keyword suppresses overflow-checking, allowing the overflow to occur without throwing an exception. This can be useful when you want to explicitly allow overflows for performance reasons or when you know the overflow behavior is safe for your specific use case.
Syntax
unchecked
{
// Code block with overflow checking disabled
}
Example: Using unchecked
Block
using System;
namespace UncheckedExample
{
class Program
{
static void Main(string[] args)
{
int max = int.MaxValue;
Console.WriteLine($"Max Value: {max}");
// This will not throw an OverflowException
int result = unchecked(max + 1);
Console.WriteLine($"Result: {result}");
}
}
}
Output
Max Value: 2147483647
Result: -2147483648
Example: Using unchecked
Statement
using System;
namespace UncheckedExample
{
class Program
{
static void Main(string[] args)
{
int max = int.MaxValue;
Console.WriteLine($"Max Value: {max}");
// This will not throw an OverflowException
int result;
unchecked
{
result = max + 1;
}
Console.WriteLine($"Result: {result}");
}
}
}
Output
Max Value: 2147483647
Result: -2147483648
Practical Use Cases
Ensuring Safety with checked
Use checked
when you want to ensure that your arithmetic operations do not overflow, which can be particularly important for financial calculations or other critical applications where incorrect values could cause significant issues.
Example
using System;
namespace FinancialCalculation
{
class Program
{
static void Main(string[] args)
{
try
{
int balance = 1000000;
int deposit = int.MaxValue;
// Ensuring no overflow occurs during the addition
int newBalance = checked(balance + deposit);
Console.WriteLine($"New Balance: {newBalance}");
}
catch (OverflowException ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}
}
}
}
Output
Exception caught: Arithmetic operation resulted in an overflow.
Performance Optimization with unchecked
Use unchecked
when you know that overflow is either safe or acceptable and you want to avoid the performance overhead of checking for overflow.
Example
using System;
namespace PerformanceOptimization
{
class Program
{
static void Main(string[] args)
{
int max = int.MaxValue;
// Allowing overflow for performance reasons
int result = unchecked(max + 1);
Console.WriteLine($"Result: {result}");
}
}
}
Output
Result: -2147483648
Conclusion
The checked
and unchecked
keywords in C# provide control over overflow-checking for arithmetic operations and conversions. Use checked
to ensure that overflow conditions are caught and handled appropriately, and use unchecked
when you want to allow overflows to occur without throwing exceptions, typically for performance reasons. Understanding when and how to use these keywords can help you write safer and more efficient code.