string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";

Console.WriteLine(GetWeatherDisplay(15));  // output: Cold.
Console.WriteLine(GetWeatherDisplay(27));  // output: Perfect!

이 코드에서 tempInCelsius < 20.0이 조건입니다. 사실이면 "Cold"로, 거짓이면 "Perfect!"로 인쇄됩니다.

condition ? A : B

조건이 사실이면 A를 선택합니다.
조건이 거짓이면 B에 해당합니다.

 

난수 예제를 사용한 분석은 다음과 같다:

var rand = new Random();
var condition = rand.NextDouble() > 0.5;

int? x = condition ? 12 : null;

IEnumerable<int> xs = x is null ? new List<int>() { 0, 1 } : new int[] { 2, 3 };

조건이 참이면 x는 값 12를 얻고, 거짓이면 null이 된다.
그런 다음 x가 null인지 아닌지에 따라 x는 다른 컬렉션을 할당받는다.

이 문구를 기억하세요: 
"이 조건이 사실인가요? 네, 그럼 이렇게 하세요; 아니요, 그럼 그렇게 하세요."

 

int[] smallArray = { 1, 2, 3, 4, 5 };
int[] largeArray = { 10, 20, 30, 40, 50 };

int index = 7;
ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);
refValue = 0;

index = 2;
((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100;

여기서 refValue는 조건에 따라 smallArray 또는 largeArray에 있는 요소에 대한 참조입니다.

 

언제 사용해야 하는지:
조건부 연산자를 사용하면 한 줄에 값을 할당하고 결정을 내리고 싶을 때 코드를 더 간결하게 만들 수 있습니다.

 

if 문을 사용한 예제:

int input = new Random().Next(-5, 5);

string classify;
if (input >= 0)
{
    classify = "양수";
}
else
{
    classify = "음수";
}

 

조건부 연산자를 사용하면 이와 동일합니다:

classify = (input >= 0) ? "양수" : "음수";

입력값이 0보다 크거나 같으면 비음수이고, 그렇지 않으면 negative입니다."라고 말하는 것과 같습니다

 

출처: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

 

+ Recent posts