Unchecked statement in C#

In this article we will learn about Unchecked statement in C#.
  • 2936

Introduction

The Unchecked statement is a an exception statement. Unchecked statement is used to ignore the stack overflow exception and execute the program. So we can say Unchecked statement will allow you to ignore these exceptions when these types of exceptions is raise. It can be used as an operator or a statement according to the following forms.

The unchecked statement:

unchecked block

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Checked_Statements

{

    class Program

    {

        static void Main(string[] args)

        {

            int number;

            // assign maximum value

            number = int.MaxValue;

            try

            {

                unchecked

                {

                    // forces stack overflow exception

                    number = number + 1;

                    Console.WriteLine(number);

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.ToString());

            }

            Console.ReadLine();

        }

    }

}

The output of the following program

Clipboard183.jpg

In this example , the output should be 2147483648 but the output is -2147483648.

© 2020 DotNetHeaven. All rights reserved.