Casting Y or N to bool C#

前端 未结 10 2212
故里飘歌
故里飘歌 2021-02-07 05:46

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);
         


        
10条回答
  •  心在旅途
    2021-02-07 06:06

    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.

提交回复
热议问题