checked keyword

Using checked keyword, we can force the compile to throw an exception if a data type is filled with data beyond its capacity. In the following example, the maximum capacity of byte data type is 255. However, if we add more values in it, this will lead to storage of garbage value in it as it crosses the capacity of byte. However, this “over flow” is not shown as error or warning by C# which can be dangerous. Therefore, when we enclose it in checked {} block, the overflow exception will be thrown.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Program
    {
        

        static void Main(string[] args)
        {
            byte b = 255;

            checked
            { 
            b++;
            }
            // b++;
            // b++;

            Console.WriteLine(b);
        }

    }
}

 

 

Tags:, ,

Add a Comment

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