In this chapter you will learn:
- What is the checked statement in C#?
- What is the benefit of using checked statement in C#?
- How to use checked statement in C# programming?
The checked statements force C# to raise exception whenever underflow or stack overflow exception occurs due to integral type arithmetic or conversion issues.
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Checked_Statement { class Program { static void Main(string[] args) { int num; // assign maximum value num = int.MaxValue; try { checked { // forces stack overflow exception num = num + 1; Console.WriteLine(num); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.ReadLine(); } } }
This program raises exception while executing because it is using checked statement that prevent the current execution when stack overflow exception appears.
Output
System.OverflowException: Arithmetic operation resulted in an overflow.
at Checked_Statements.Program.Main<String[] args> in C:Documents and Settings\Steven\My Documents\Visual Studio 2008\Projects\complete c# code\Chapter4\Checked Statements\Checked Statements\Program.cs:line 18
__
Summary
In this chapter you learned what checked statement is and also learned how to use checked statement in C sharp programming. In next chapter you will learn about Unchecked Statement in C#.