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
}
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
.
bool theanswer = input.ToLower() == "y";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With