|| 연산자(C# 참조)
업데이트: 2007년 11월
조건부 논리 OR 연산자(||)는 bool 피연산자의 논리 OR을 수행하지만 둘째 피연산자는 필요한 경우에만 계산합니다.
설명
아래 연산은
x || y
다음 연산에 해당하지만
x | y
x가 true인 경우 y 값에 관계없이 논리 OR 연산의 결과가 true이기 때문에 y를 계산하지 않는다는 점이 다릅니다. 이것을 "단락(short-circuit)" 계산이라고 합니다.
조건부 논리 OR 연산자는 오버로드할 수 없지만, 일반적인 논리 연산자와 true 및 false 연산자의 오버로드가 조건부 논리 연산자의 오버로드로 간주됩니다. 이 경우 일부 제한이 있습니다.
예제
다음은 || 연산자를 사용한 식에서 첫째 피연산자만 계산하는 경우의 예입니다.
class NullCoalesce
{
static int? GetNullableInt()
{
return null;
}
static string GetStringValue()
{
return null;
}
static void Main()
{
// ?? operator example.
int? x = null;
// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;
// Assign i to return value of method, unless
// return value is null, in which case assign
// default value of int to i.
int i = GetNullableInt() ?? default(int);
string s = GetStringValue();
// ?? also works with reference types.
// Display contents of s, unless s is null,
// in which case display "Unspecified".
Console.WriteLine(s ?? "Unspecified");
}
}