Ternary conditional operator
Peponi │ 11/14/2024 │ 2m
C#
SyntaxOperator?:
Ternary conditional operator
11/14/2024
2m
Peponi
C#
SyntaxOperator?:
1. 삼항 연산자
삼항 연산자 (?:
) 는 boolean 식
을 계산한 이후 반환 값에 따라 결과를 반환한다. 삼항 연산자의 사용 방법은 아래와 같다.
Condition ? True : False
Condition
은boolean 식
이며, 계산 결과가true
일 때는True 항
이 반환되고false
일 때는False 항
이 반환된다.
삼항 연산자는 왼쪽에서부터 오른쪽으로 연산을 수행한다.
static void Main(string[] args)
{
int A = 1;
Console.WriteLine(IsZero(A) ? "0" : IsOne(A));
bool IsZero(int x)
{
Console.WriteLine(nameof(IsZero));
return x == 0;
}
bool IsOne(int x)
{
Console.WriteLine(nameof(IsOne));
return x == 1;
}
}
/* output:
IsZero
IsOne
True
*/
다음 예제에서와 같이, 삼항 연산자를 이용하여 if 문을 대체하는 경우 코드가 간결해질 수 있다.
static void Main(string[] args)
{
int A = 2;
// If 문
if (A == 0)
{
Console.WriteLine(0);
}
else if (A == 1)
{
Console.WriteLine(1);
}
else
{
Console.WriteLine(2);
}
// 삼항 연산자
Console.WriteLine(A == 0 ? 0 : A == 1 ? 1 : 2);
}
2. 조건부 참조 식
ref
키워드를 이용하여 조건부 참조 식의 결과를 활용할 수 있다. 조건부 참조 식의 사용 방법은 아래와 같다.
Condition ? ref True : ref False
static void Main(string[] args)
{
int A = 10;
int B = 20;
int X = 15;
// B의 참조를 Y에 할당
ref int Y = ref (X < 10 ? ref A : ref B);
Console.WriteLine(Y);
Y = 0;
Console.WriteLine(B);
}
/* output:
20
0
*/