Checked and Unchecked In C#

Checked and Unchecked In C#

 

In this article, you will lean, Checked and Unchecked In C#, the checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.

 

C# Checked Example

using System;  
namespace usingcsharp
{  
    class Program  
    {  
        static void Main(string[] args)   
        {  
            checked  
            {  
                int val = int.MaxValue;  
                Console.WriteLine(val + 2);  
            }  
        }  
    }  
}  

 

C# Unchecked Example

 

using System;  
namespace usingcsharp
{  
    class Program  
    {  
        static void Main(string[] args)   
        {  
            unchecked  
            {  
                int val = int.MaxValue;  
                Console.WriteLine(val + 2);  
            }  
        }  
    }  
}  

 

Console.WriteLine(checked(2147483647 + ten));

// Checked block.
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}

 

 

2021-10-03