C# Checked Statement

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

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.