When using the ternary operator in C#, sometimes the expression producing the value to be evaluated can be quite long. Is there a way to get its value in one of the result expressions?
For example, if I have the ternary expression:
bool? foo = model.People.SingleOrDefault(x => x.Age > 21 && x.Name.StartsWith("Jo")) == null ? null : model.People.SingleOrDefault(x => x.Age > 21 && x.Name.StartsWith("Jo")).IsEnabled == "true";
Is there a way not to have to repeat the expression getting the item from the list in the second result expression? The only way I can think of to do this is to add an extra line:
var item = model.People.SingleOrDefault(x => x.Age > 21 && x.Name.StartsWith("Jo"));
bool? foo = item == null ? null : item.IsEnabled == "true";
I've read the Microsoft docs and can't see any suggestion as to how this could be done. I'm thinking it isn't currently possible, which is a shame!
You can use the ? operator as below in C# 8 and later.
bool? foo = model.People.SingleOrDefault(x => x.Age > 21 && x.Name.StartsWith("Jo"))?.IsEnabled.Equals("true");
Or you can keep the two line form, which I find a bit clearer:
var item = model.People.SingleOrDefault(x => x.Age > 21 && x.Name.StartsWith("Jo"));
var foo = item?.IsEnabled.Equals("true"); // foo is a bool?