Search code examples
c#boolean

C# prompting for a boolean value


My searches have come up blank, or I am just not understand the results that I am finding. I am trying to prompt the user to input a boolean value, but I want the answer to be yes or no. Let me know if you need to see more code but I have this for the prompt.

public static bool getBoolInputValue(string inputType)
    {
        bool valid = false;
        bool value = true;
        string inputString = string.Empty;
        do
        {
            inputString = GetInput(inputType);
            if (!(String.IsNullOrEmpty(inputString)))
            {
                valid = bool.TryParse(inputString, out value);
            }
            if (!valid)
                Console.WriteLine("Invalid " + inputType + " try again!");
        } while (!valid);

        return value;
    }

This is the paramater for my boolean. Maybe this needs to be more specific?

public bool Nitrus
    {
        set { nitrus = value; }
        get { return nitrus; }
    }

Thank you for the help. I am fairly new to programming but cannot figure this out. It does prompt successfully, but it does not matter what answer I put into the box, it tells me it is not the right format.


Solution

  • If I understand correctly you want the user to type in "yes" and that will mean you have a True value. If that is correct, skip all the string.IsNullOrEmpty and bool.TryParse stuff and do something more like this.

    //make it ToLower so that it will still match if the user inputs "yEs"
    inputString = GetInput(inputType);
    if (inputString.ToLower() == "yes")
    {
      value = true;
    }
    else
    {
      value = false;
    }
    
    //note that the if/else code is the same as directly applying 
    // the value from the comparison itself:
    // value = inputString.ToLower() == "yes";
    
    // this allows the user to type in "yes" or "y":
    // value = inputString.ToLower() == "yes" || inputString.ToLower() == "y";