C
C#•2y ago
fatsuperman.

How to combine null coascence and ternary operator?

Hello, I have a string variable A. And I want to fill thid string A with value Yes if a bool is true, No if bool is false and empty string if bool is null, how do I do this in 1 line
10 Replies
Akseli
Akseli•2y ago
guessing your bool is a bool? (nullable bool) since a normal bool cant be null, only false or true
fatsuperman.
fatsuperman.•2y ago
Yeah So i want to check if true false or null on 1 line
Pobiega
Pobiega•2y ago
double ternary.
Akseli
Akseli•2y ago
you could do nested ternary, or if you allow a weird switch statement
Pobiega
Pobiega•2y ago
var x = tfn == null ? string.Empty : tfn ? "Yes" : "No";
var x = tfn == null ? string.Empty : tfn ? "Yes" : "No";
but yeah, please use a switch expression
fatsuperman.
fatsuperman.•2y ago
right now I have: variable == null ? " " : (bool)variable ? "YES" : "NO"
Akseli
Akseli•2y ago
a switch expression
fatsuperman.
fatsuperman.•2y ago
It says I have to cast tfn @Pobiega
Pobiega
Pobiega•2y ago
bool? tfn = true;

string output = tfn switch
{
true => "Yes",
false => "No",
null => string.Empty
};
bool? tfn = true;

string output = tfn switch
{
true => "Yes",
false => "No",
null => string.Empty
};
this is the cleanest way for sure
var x = !tfn.HasValue ? string.Empty : tfn.Value ? "Yes" : "No";
var x = !tfn.HasValue ? string.Empty : tfn.Value ? "Yes" : "No";
I just yolo-coded it here in discord, sorry 😛 this is the nested ternary version but the above is nicer the switch expression one is so much nicer, it shows clearly whats going on and isnt confusing to read
fatsuperman.
fatsuperman.•2y ago
Thank you, you have given great answers.