Tags

No tags have been created or used yet.

News

March 2008 - Posts

Checked Keyword
I recently discovered the “checked” keyword which is used to throw an exception when arithmetic overflow occurs. This is important as .net automatically narrows data types which could lead to overflow problems. The following example shows how this situation could arise:

class Program
{
    static void Main(string[] args)
    {
       int value1 = 100000;
       int value2 = 200000;

       short value3 = (short)Add(value1, value2);

       Console.WriteLine(value3);
     }

     static int Add(int x, int y) { 
       return x + y; }
}

Note that this code will compile cleanly at appears to be valid. However, casting the Add result to a short results in an overflow condition that will not be detected at run-time. This can be trapped by using the checked keyword thus:

class Program
{
    static void Main(string[] args)
    {
        int value1 = 100000;
        int value2 = 200000;

        short value3 = checked((short)Add(value1, value2));

        Console.WriteLine(value3);
     }

     static int Add(int x, int y) { 
        return x + y; }
}