.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# Checked and Unchecked
C# Checked and Unchecked
C# provides checked and unchecked keyword to handle integral type exceptions. Checked and unchecked keywords specify checked context and unchecked context respectively. In checked context, arithmetic overflow raises an exception whereas, in an unchecked context, arithmetic overflow is ignored and result is truncated.
C# Checked
The checked keyword is used to explicitly check overflow and conversion of integral type values at compile time.
Let's first see an example that does not use checked keyword.
C# Checked Example without using checked
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
Output:
See, the above program produces the wrong result and does not throw any overflow exception.
C# Checked Example using checked
This program throws an exception and stops program execution.
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
checked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output:
C# Unchecked
The Unchecked keyword ignores the integral type arithmetic exceptions. It does not check explicitly and produce result that may be truncated or wrong.
Example
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
unchecked
{
int val = int.MaxValue;
Console.WriteLine(val + 2);
}
}
}
}
Output: