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#.