Checked and Unchecked : checked unchecked « Data Types « C# / C Sharp






Checked and Unchecked



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

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Max value of byte is {0}.", byte.MaxValue);
        Console.WriteLine("Min value of byte is {0}.", byte.MinValue);
        byte b1 = 100;
        byte b2 = 250;

        try {
            checked {
                byte sum = (byte)(b1 + b2);
                byte b4, b5 = 100, b6 = 200;
                b4 = (byte)(b5 + b6);
                Console.WriteLine("sum = {0}", sum);
            }
        } catch (OverflowException e) {
            Console.WriteLine(e.Message);
        }

        unchecked {
            byte sum = (byte)(b1 + b2);
            Console.WriteLine("sum = {0}", sum);
        }
    }
}

       








Related examples in the same category

1.OverflowCheck
2.Checking for overflows.
3.unchecked int overflow
4.Operators and Expressions:Checked and Unchecked Expressions
5.Demonstates using checked keyword to detect an overflowDemonstates using checked keyword to detect an overflow
6.Demonstates using checked keyword to detect an overflow 2Demonstates using checked keyword to detect an overflow 2