wonea wonea -4 years ago 77
C# Question

Casting Y or N to bool C#

Just for neatness sake I was wondering, whether it's possible to cast Y or N to a bool? Something like this;

bool theanswer = Convert.ToBoolean(input);


The long version;

bool theanswer = false;
switch (input)
{
case "y": theanswer = true; break;
case "n": theanswer = false; break
}

Answer Source

No, there's nothing built in for this.

However, given that you want to default to false, you can just use:

bool theAnswer = (input == "y");

(The bracketing there is just for clarity.)

You may want to consider making it case-insensitive though, given the difference between the text of your question and the code you've got. One way of doing this:

bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);

Note that using the specified string comparison avoids creating a new string, and means you don't need to worry about cultural issues... unless you want to perform a culture-sensitive comparison, of course. Also note that I've put the literal as the "target" of the method call to avoid NullReferenceException being thrown when input is null.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download