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));
- [2018/02/26] List 에서 고유값 얻기 (4040)
- [2015/05/22] C#, 아두이노 간의 WIFI 통신으로 LCD 제어 (4568)
- [2015/03/13] 항상 마지막에 추가한 TEXT 보이게 (15800)
- [2014/01/17] ComboBox Text 편집 안되게 (14508)
- [2014/01/08] if 문에서 여러개 비교할때 () *3
- [2013/12/30] C++, C# 간단한 기능 비교 ()
- [2013/12/18] 3자리마다 ,(콤마) 찍기 (원화, 달러 표시) (15239)
- [2013/09/29] 설치된 IE 버전 얻기 ()
- [2013/08/29] byte array to Hexa String (13039)
- [2013/06/25] string array to string (스트링 문자열 합치기) (23727)