C# Unchecked Statement

In this chapter you will learn:
  • What is unchecked statement in C#?
  • What is the advantage and disadvantage of Unchecked Statement?
  • How to use unchecked statement in C sharp programming?

The unchecked statement ignores the stack overflow exception and executes the program so, the output can be incorrect.

Example:

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

namespace Unchecked_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            int num;
            // assign maximum value
            num = int.MaxValue;
            try
            {
                unchecked
                {
                    // forces stack overflow exception
                    num = num + 1;
                    Console.WriteLine(num);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadLine();
        }
    }
}

 

Here, the correct output should be 2147483648 but the output is -2147483648 which is wrong because of unchecked statements as it ignores exception and put output on screen.

Output

-2147483648
__

Summary

In this chapter you learned what unchecked statement is in C# and how to use it in programming. In next chapter you will learn about Lock Statement in C#.

More Articles

 

Share your thought



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.