Checking for overflows. : checked unchecked « Data Types « C# / C Sharp






Checking for overflows.

 


using System;
public class MainClass {
    public int CheckedAddition(short s1, short s2) {
        int z = 0;
        try {
            z = checked((short)(s1 + s2));
        } catch (OverflowException) {
            Console.WriteLine("Overflow Exception, Returning 0");
        }
        return z;
    }
    public int UncheckedAddition(short s1, short s2) {
        int z = ((short)(s1 + s2));
        return z;
    }

    public static void Main() {
        MainClass app = new MainClass();
        short s1 = 32767;
        short s2 = 32767;

        Console.WriteLine("Checked Addition is: {0}",app.CheckedAddition(s1, s2));
        Console.WriteLine("Unchecked Addition is: {0}",app.UncheckedAddition(s1, s2));
    }
}

 








Related examples in the same category

1.OverflowCheck
2.Checked and Unchecked
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