kus
I have an object, lets say serviceData that has a nullable boolean property, lets call it Potato. I want to create a string that says `yes` if Potato is true and `no` if Potato is false.
I originally wrote
```csharp
string potato= "";
if (serviceData.Potato ?? false)
{
potato = "Yes";
}
else
{
if (serviceData.Potato ?? true == false)
{
potato = "No";
}
}
```
but then I realized, with Jack Douglas' help that I could write
```csharp
string potato= "";
if (serviceData.Potato == true)
{
potato = "Yes";
}
if (serviceData.Potato == false)
{
potato = "No";
}
```
However, I was convinced that there has to be a "better" way to write this and therefore I asked this question in the chat where Jack encouraged me to add this as a question so we could document it for the future.
Thanks, Jack!
Top Answer
Jack Douglas
With C# 8 you can use the [new 'switch expressions' feature](https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions):
> Often, a `switch` statement produces a value in each of its `case` blocks. **Switch expressions** enable you to use more concise expression syntax. There are fewer repetitive `case` and `break` keywords, and fewer curly braces.
So you can use this one-liner:
```
potato = serviceData.Potato switch { true => "Yes", false => "No", _ => "" }
```
Answer #2
Josh Darnell
In case you don't have access to the new switch expressions feature, you can achieve something close to the brevity of Jack's answer with a couple of ternary operators (one to handle the `null` case, and one to handle the `true` / `false` cases):
```
string potato = !serviceData.Potato.HasValue
? ""
: serviceData.Potato.Value
? "Yes"
: "No";
```
Answer #3
Anonymous 12265
`
string potato= "";
if (serviceData.Potato == null)
{
potato = "";
}
else if (serviceData.Potato == false)
{
potato = "No";
}
else
{
potato = "Yes";
}`
is this fine?