Pete
Pete

Reputation: 3451

How to output to console a bool?

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

Answers (3)

Pavel Anikhouski
Pavel Anikhouski

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 the HasValue property is true, or an empty string ("") if the HasValue property is false.

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

jfiggins
jfiggins

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

Alex - Tin Le
Alex - Tin Le

Reputation: 2000

string output = boolValNullable?.ToString() ?? "null"

Upvotes: 15

Related Questions