While or and not equal to not working?

24,415

Solution 1

If you want to come out of the loop, when the User enters Exit or Test then you need the && operator not ||

while ((var_app_choice != "Exit") && (var_app_choice != "Test"))
    {
        var_app_choice = Console.ReadLine();
        //stuff
    }

Solution 2

I think you want and not or...

If the value of var_app_choice is "Test", then the first condition is true and the loop will execute. Similarly, if it's "Exit", then the second condition is true. In other words, you have an infinite loop...

Share:
24,415
chilly8063
Author by

chilly8063

Updated on July 09, 2022

Comments

  • chilly8063
    chilly8063 almost 2 years

    Im quite new to C# and am trying to write a super simple loop

            while ((var_app_choice != "Exit") || (var_app_choice != "Test"))
            {
                //stuff
            }
    

    I have a console application where an end user will input a value

    If this value is not equal (!=) to Exit OR Test then it should loop.

    What am i doing wrong here?

    Thanks

  • chilly8063
    chilly8063 over 11 years
    I think I need more sleep! This is exactly what I was looking for, thanks!
  • Habib
    Habib over 11 years
    @user1718989, you are welcome, and Welcome to StackOverflow :)
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 11 years
    According to De Morgan's law this can also be written: while (!(var_app_choice == "Exit" || var_app_choice == "Test")) { ... }. The "not" operator ! has been "pulled out", and "and" changed to "or".
  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 11 years
    I agree your version is most clear. I just wanted to give another formal expression of "the choice is not Exit or Test".