Pro Ep 22 : Ternary Conditional ?: Operator in C#
Published in
1 min readMar 7, 2023
♉ Using ternary conditional operator we can make our code shorter and more readable.
♉ It saves us from multiple lines of if-else.
♉ It works like : — 𝚌𝚘𝚗𝚍𝚒𝚝𝚒𝚘𝚗 ? 𝚌𝚘𝚗𝚜𝚎𝚚𝚞𝚎𝚗𝚝 : 𝚊𝚕𝚝𝚎𝚛𝚗𝚊𝚝𝚒𝚟𝚎
♉ Its recommended to use when action after the condition is shorter.
♉ We can use it for multiple levels as well
𝚟𝚊𝚛 𝚜𝚘𝚖𝚎𝚝𝚑𝚒𝚗𝚐 = 𝚏𝚘𝚘 ? 𝟷 :
𝚋𝚊𝚛 ? 𝟸 :
𝚋𝚊𝚣 ? 𝟹 :
𝟺;
♉ It works efficiently with expression bodied methods e.g.
𝚜𝚝𝚛𝚒𝚗𝚐 𝙶𝚎𝚝𝙳𝚛𝚒𝚗𝚔(𝙳𝚊𝚢𝙾𝚏𝚆𝚎𝚎𝚔 𝚍𝚊𝚢) =>
𝚍𝚊𝚢 == 𝙳𝚊𝚢𝙾𝚏𝚆𝚎𝚎𝚔.𝙵𝚛𝚒𝚍𝚊𝚢 ? “𝙻𝚎𝚖𝚘𝚗𝚊𝚍𝚎” : “𝙲𝚘𝚏𝚏𝚎𝚎”;
𝐃𝐚𝐲𝐎𝐟𝐖𝐞𝐞𝐤 is enum available in .NET
If you want to help the author in growing
- Subscribe my YouTube Channel where I would be sharing videos on .NET
- Subscribe my Weekly .NET Newsletter of C#/.NET
- Download my eBook at Gum road that contains 30+ .NET Tips.
- Become Patron to get access to 80+ Compiled Questions and Answers at one place