Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Y or N to bool C#

Tags:

c#

c#-4.0

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
}
like image 442
wonea Avatar asked Sep 15 '10 10:09

wonea


3 Answers

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.

like image 86
Jon Skeet Avatar answered Oct 06 '22 21:10

Jon Skeet


bool theanswer = input.ToLower() == "y";
like image 25
Joel Etherton Avatar answered Oct 06 '22 19:10

Joel Etherton


As suggested by Jon, there's nothing inbuilt like this. The answer posted by John gives you a correct way of doing. Just for more clarification, you can visit:

http://msdn.microsoft.com/en-us/library/86hw82a3.aspxlink text

like image 38
sumit_programmer Avatar answered Oct 06 '22 20:10

sumit_programmer