'Is there a way to compress a check that returns a nullable boolean this into 1-2 lines?
I'm making a simple C# console app and the user has to input either a 1 or a 2 to select their option, and obviously since the user can enter absolutely anything, I need to make a check that returns their input and if it isn't a 1 or a 2, it'll return null.
This is what I made
bool? getResponse = null;
if (read == "1")
{
getResponse = true;
}
else if (read == "2")
{
getResponse = false;
}
else
{
getResponse = null;
}
Knowing C#, there's definitely a way to simplify this but I cant seem to find a way to online. Any pointers?
Solution 1:[1]
Probably you are looking for conditional operator ?:.
But this could be complex to maintain and difficult to read if the logic is getting complex (adding logic for read == "3" and etc.).
getResponse = read == "1"
? true
: read == "2"
? false
: null;
Another approach you can apply is switch expression for C# 9.
getResponse = read switch
{
"1" => true,
"2" => false,
_ => null,
};
The third approach is you work around with Dictionary.
using System.Collections.Generic;
using System.Linq;
Dictionary<string, bool> resultDict = new Dictionary<string, bool>
{
{ "1", true },
{ "2", false }
};
getResponse = resultDict.TryGetValue(read, out bool _result)
? _result
: null;
Solution 2:[2]
You can use ternary operator in a such situations like this
string read = Console.ReadLine();
bool? response = read == "1" ? true
: read == "2" ? false : null;
but it's best when there is only 2 possible ways, as u can see it's getting out of hand easily. In this situation my code above is ok, but if you have like 10 possibilities maybe something like this is a good approach
// lets say there is ways
// 1 = true, 2 = false, 3 = null
// and any other input means exception
string read = Console.ReadLine()!;
Dictionary<string, bool?> keyValues = new();
keyValues.Add("1", true);
keyValues.Add("2", false);
keyValues.Add("3", null);
bool? response = keyValues.ContainsKey(read) ? keyValues[read]
: throw new Exception();
the exception here is just for example, my point is that when you have multiple possibilities doing such thing with dictionary seems much cleaner than if/else, switch/case or multiconditional ternery operator
Solution 3:[3]
I consider this pretty unreadable, but it avoids the nested ternary.
getResponse = int.TryParse(read, out var i) && i > 0 && i < 3 ? (bool)(2-i) : null;
Parse the string into an int, make sure it is the valid range, and then do some math so you can cast it to a bool. When casting an integer type to a bool, 0 means false, and non-zero means true.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Chestera |
| Solution 3 |
