Reputation: 3451
I want a concise way to output a bool? in c#. Currently, I am doing this which is very bulky.
string outputString = boolValNullable.HasValue && boolValNullable.Value ? "true" : "false";
I want to do something like:
string outputString = boolValNullable ?? "null"
The above is invalid syntax.
Upvotes: 2
Views: 3571
Reputation: 23228
Actually, you can use a conditional operator ?:
for that
string outputString = boolValNullable.HasValue ? boolValNullable.Value.ToString() : "null";
or simply use Nullable<T>.ToString()
method, if you want to get an empty string in case of boolValNullable
equals null
string outputString = boolValNullable.ToString();
It returns
The text representation of the value of the current
Nullable<T>
object if theHasValue
property istrue
, or an empty string ("") if theHasValue
property isfalse
.
Boolean.ToString
method returns either True
of False
(the first letter is capital). If you need a lower case, you should add ToLower()
call after ToString()
Upvotes: 1
Reputation: 129
This should do the trick for you. Pass in your bool to this method and it will output to your console.
public void OutputBoolToConsole(bool? myBool)
{
var myBoolAsString = myBool?.ToString() ?? "bool is null";
Console.WriteLine(myBoolAsString);
}
Upvotes: 1