C# Advanced (Series #3)

1 min read

c#
  • C# – Anonymous Types
  • C# – Dynamic Types
  • C# – Ternary Operator ?:
  • C# Generics & Generic Constraints
  • C# – Delegates
  • C# – Func Delegate
  • C# – Action Delegate
  • C# – Anonymous Method
  • C# – Events
  • C# – Extension Method
  • C# – HttpClient

C# – Ternary Operator?:

C# bao gồm decision-making operator ?: được gọi là toán tử điều kiện hoặc toán tử ba ngôi. Đây là dạng rút gọn của điều kiện if else.

// Syntax
condition ? statement 1 : statement 2

Toán tử ba ngôi bắt đầu bằng điều kiện boolean. Nếu điều kiện này được đánh giá là đúng thì nó sẽ thực thi câu lệnh đầu tiên sau ?, nếu không thì câu lệnh thứ hai sau : sẽ được thực thi.

Ví dụ sau đây minh họa toán tử ba ngôi.

// Example: Ternary operator
int x = 20, y = 10;
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
/*Output
x is greater than y
*/

Ở trên, biểu thức điều kiện x > y trả về true, vì vậy câu lệnh đầu tiên sau ? sẽ được thực thi.

Sau đây thực hiện câu lệnh thứ hai

// Example: Ternary operator
int x = 10, y = 100;
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
/*Output
x is less than y
*/

Vì vậy, toán tử ba ngôi là dạng viết tắt của câu lệnh if else. Ví dụ trên có thể được viết lại bằng điều kiện if else

Toán tử ba ngôi lồng nhau

Có thể sử dụng các toán tử bậc ba lồng nhau bằng cách đưa biểu thức điều kiện làm câu lệnh thứ hai.

// Example: Nested ?:
int x = 10, y = 100;
string result = x > y ? "x is greater than y" : 
                    x < y ? "x is less than y" : 
                        x == y ? "x is equal to y" : "No result";
Console.WriteLine(result);

Toán tử ba ngôi có tính right-associative. Biểu thức a ? b : c ? d : e được đánh giá là ? b : (c ? d : e), không phải là (a ? b : c) ? d: đ.

// Example: Nested ?:
var x = 2, y = 10;
var result = x * 3 > y ? x : y > z? y : z;
Console.WriteLine(result);
Avatar photo

𝐌𝐄𝐙𝐎𝐍 – 𝐓𝐇𝐄 𝐔𝐋𝐓𝐈𝐌𝐀𝐓𝐄 𝐏𝐋𝐀𝐓𝐅𝐎𝐑𝐌 𝐅𝐎𝐑 𝐂𝐎𝐌𝐌𝐔𝐍𝐈𝐓𝐈𝐄𝐒 & 𝐁𝐔𝐒𝐈𝐍𝐄𝐒𝐒

Discord is a widely used communication platform, but is it truly the best solution for community and business management? While it excels in creating...
Avatar photo Ngan Ton Thuy
3 min read

𝐌𝐞𝐳𝐨𝐧 𝐯𝐬 𝐒𝐥𝐚𝐜𝐤 – 𝐖𝐡𝐢𝐜𝐡 𝐎𝐧𝐞 𝐄𝐧𝐡𝐚𝐧𝐜𝐞𝐬 𝐘𝐨𝐮𝐫 𝐁𝐮𝐬𝐢𝐧𝐞𝐬𝐬…

Both Mezon and Slack are powerful communication platforms, but which one is the right fit for your organization? Let’s compare their key features: 𝐔𝐬𝐚𝐠𝐞...
Avatar photo Ngan Ton Thuy
1 min read

Leave a Reply

Your email address will not be published. Required fields are marked *