7/26/2010

C# Checked and Unchecked Operators



Checked and Unchecked Operators:
--------------------------------
Checked Operators:
------------------ Checked operator generates an overflow exception at run time, if an exception exceeds arithmetic limit of that type.

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

namespace ConsoleApplication21
{
    class demo
    {
        static short s = 32767;

        public int find()
        {
            checked   // checked
            {
                int z = (short)(s + 12);
                return z;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            demo d=new demo();
            Console.WriteLine(d.find());
        }
    }
}


Unchecked operator:
-------------------
Unchecked operator disables the arithmetic checking at compile time and results of the most significant bits are disabled and the execution continues.

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

namespace ConsoleApplication21
{
    class demo
    {
        static short s = 32767;

        public int find()
        {
            unchecked   // unchecked
            {
                int z = (short)(s + 12);
                return z;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            demo d=new demo();
            Console.WriteLine(d.find());
        }
    }
}

No comments:

Post a Comment