Casting Y or N to bool C#

前端 未结 10 2215
故里飘歌
故里飘歌 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:09

    Create a extension method for string that does something similar to what you specify in the second algorithm, thus cleaning up your code:

    public static bool ToBool(this string input)
    {
        // input will never be null, as you cannot call a method on a null object
        if (input.Equals("y", StringComparison.OrdinalIgnoreCase))
        {
             return true;
        }
        else if (input.Equals("n", StringComparison.OrdinalIgnoreCase))
        {
             return false;
        }
        else
        {
             throw new Exception("The data is not in the correct format.");
        }
    }
    

    and call the code:

    if (aString.ToBool())
    {
         // do something
    }
    

提交回复
热议问题