Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Toán tử ba ngôi (Ternary Operator) trong C#

Toán tử ba ngôi (Conditional Operator) trong C# nhận 3 toán hạng, đánh giá biểu thức Boolean.

Ví dụ:

y = (z == 1) ? 100 : 180;

Nếu điều kiện true (1) -> lấy giá trị 2 (100). Nếu false (0) -> lấy giá trị 3 (180).

Ví dụ

using System;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            int x, y;
            x = 25;
            y = (x == 25) ? 20 : 30;
            Console.WriteLine("Value of y = {0}", y); // 20
            y = (x == 1) ? 50 : 90;
            Console.WriteLine("Value of y = {0}", y); // 90
            Console.ReadLine();
        }
    }
}

Hai điều kiện ternary: y = (x == 25) ? 20 : 30; và y = (x == 1) ? 50 : 90;