unchecked 키워드는 int 연산과 변환에서 오버플로우를 체크해줍니다.
이 키워드는 아래처럼 사용할수 있습니다.

unchecked (expression)



예제 1 )
// statements_unchecked.cs
// Using the unchecked statement with constant expressions
// Overflow is checked at compile time
using System;

class TestClass
{
   const int x = 2147483647;   // Max int
   const int y = 2;

   public int MethodUnCh()
   {
      // Unchecked statement:
      unchecked
      {
         int z = x * y;
         return z;   // Returns -2
      }
   }

   public static void Main()
   {
      TestClass myObject = new TestClass();
      Console.WriteLine("Unchecked output value: {0}",
         myObject.MethodUnCh());
   }
}

결과
Unchecked output value: -2


예제 2 )
// statements_unchecked2.cs
// CS0220 expected
// Using default overflow checking with constant expressions
// Overflow is checked at compile time
using System;

class TestClass
{
   const int x = 2147483647;   // Max int
   const int y = 2;

   public int MethodDef()
   {
      // Using default overflow checking:
      int z = x * y;
      return z;   // Compiler error
   }

   public static void Main()
   {
      TestClass myObject = new TestClass();
      Console.WriteLine("Default checking value: {0}",
         myObject.MethodDef());
   }
}

결과
The warning: The operation overflows at compile time in checked mode.



예제 3 )
// statements_unchecked3.cs
// CS0220 expected
// Using the checked statement with constant expressions
// Overflow is checked at compile time
using System;

class TestClass
{
   const int x = 2147483647;   // Max int
   const int y = 2;

   public int MethodCh()
   {
      // Checked statement:
      checked
      {
         int z = (x * y);
         return z;   // Compiler error
      }
   }

   public static void Main()
   {
      TestClass myObject = new TestClass();
      Console.WriteLine("Checked value: {0}", myObject.MethodCh());
   }
}

결과
The warning: The operation overflows at compile time in checked mode.


또한 int 값을 포인터로 변환할때 많이 사용됩니다.
        private static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
        private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
        private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
        private static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
        private static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));

+ Recent posts