C#/.NET(19): ternary 연산자(?:)
ternary 연산자(?:) 의 기능
ternary 연산자를 사용하면, if-else 로 작성된 코드를 줄일 수 있다.
ternary 는 비교식이 참인 경우, 불타입을 리턴하여 문장을 실행한다.
ternary 연산자 포맷
var [object] = [비교식] ? [true 실행문] : [false 실행문]
[ternary (if-else) - 예시 코드]
using System;
using static System.Console;
namespace ternaryOperator
{
class Dog
{
internal double _weight;
internal Dog(double weight)
{
_weight = weight;
}
}
internal class Program
{
static void Main(string[] args)
{
var dog = new Dog(30);
//string size;
//if (dog._weight > 25)
//{
// size = "big";
//}
//else
//{
// size = "small";
//}
//Write($"The dog is {size}");
var size = dog._weight > 25 ? "big" : "small";
Write($"The dog is {size}");
}
}
}
[ternary (if-else if-else) - 예시 코드]
using System;
using static System.Console;
namespace ternaryOperator
{
class Dog
{
internal double _weight;
internal Dog(double weight)
{
_weight = weight;
}
}
internal class Program
{
static void Main(string[] args)
{
var dog = new Dog(20);
//string size;
//if (dog._weight > 25)
//{
// size = "big";
//}
//else if (dog._weight > 20)
//{
// size = "normal";
//}
//else // dog._weight < 10
//{
// size = "small";
//}
//Write($"The dog is {size}");
var size = dog._weight > 25 ? "big" : dog._weight < 10 ? "small" : "normal";
Write($"The dog is {size}");
}
}
}
댓글남기기