Home [C# 筆記] 三元表達式 ? :
Post
Cancel

[C# 筆記] 三元表達式 ? :

三元表達式,就是 if-else 的簡化寫法

表達式1 ? 表達式2: 表達式3
判斷條件 ? 成立 : 不成立

1
bool result = 5 > 3 ? true : false;

只要是可以用在 if-else 都可以用三元表達式

練習: 計算兩個數的大小,求出最大

1
2
3
4
int x = 10;
int y = 20;
int max = x > y ? x : y;
Console.WriteLine(max);

conditional-operator

This post is licensed under CC BY 4.0 by the author.