Home > Net >  Bool method keeps returning false
Bool method keeps returning false

Time:11-08

So this code checks to make sure the user has entered a proper math operator in my calculator, but no matter what I seem to do the code ALWAYS gives me false and it's driving me nuts.

if (IsOperator(txtOperator.ToString(), "Operator")




        public bool IsOperator(string textBox, string name)
        {
            switch (textBox)
            {
                case "*":
                    return true;
                case "x":
                    return true;
                case "/":
                    return true;
                case " ":
                    return true;
                case "-":
                    return true;
            }
                MessageBox.Show(name   " must be a valid math operator.", "Entry Error");
                return false;
        }

CodePudding user response:

I think you need txtOperator.Text instead of txtOperator.ToString() in the call to IsOperator, assuming txtOperator is a TextBox.

Have you already debugged the app and inspected the value?

CodePudding user response:

Probably you just need to pass in the the Text property of that textbox...

   if (IsOperator(txtOperator.Text, "Operator")) { ...

The method itself could be optimized to sth like:

    public bool IsOperator(string textEntered, string name)
    {
        switch (textEntered?.Trim())
        {
            case "*":
            case "x":
            case "/":
            case " ":
            case "-":
                return true;

            default:
                MessageBox.Show(name   " must be a valid math operator", "Entry Error");
                return false;

        }
    }
  • Related