Risho
Risho

Reputation: 2647

Testing for two conditions in one IF statement

I realize this like the Hello World level issue but I have to ask. Can these two condition be simplified into one if statament?

bool isChecked = false;

if(Request["foo"] != null) // Check box
      isChecked = (Request["foo"].ToLower() == "on");

if (!isChecked)
      // do stuff

Individually, I get true in both instances, but when I add them onto one if statement joined with && I don't get the same outcome.

if(Request["foo"] != null && (Request["foo"].ToLower() == "on"))
          // do stuff

Upvotes: 0

Views: 113

Answers (4)

musefan
musefan

Reputation: 48415

It is easier to follow the logic if you simplify it in steps...

first you can shorten your assignment of isChecked as follows:

bool isChecked = Request["foo"] != null && Request["foo"].ToLower() == "on";

if (!isChecked)
      // do stuff

Then we just need to get rid of the isChecked variable, which can be done with a simple swap:

if (!(Request["foo"] != null && Request["foo"].ToLower() == "on"))
      // do stuff

That makes it a bit harder to read and understand, so let's simplify it a bit further. Assuming we have the rule of "do something if Request["foo"] is not set to on" (which is basically what your original logic is doing) then we can do this:

if (Request["foo"] == null || Request["foo"].ToLower() != "on"))
      // do stuff

Upvotes: 2

bmm6o
bmm6o

Reputation: 6505

You can combine the two tests into:

bool isChecked = Request["foo"] != null && Request["foo"].ToLower() == "on";

You can also have them in the predicate of an if statement. The reason you can do this is that in C# the && and || operators "short-circuit". That means that if the value of the whole expression can be determined from the left side, the right side is not evaluated. This is important because in the case where Request["foo"] is null, you would get an null reference exception if the right side were evaluated. Testing for null on the left side of an && or || is a very common idiom in all of the C-derived languages.

Upvotes: 1

ansible
ansible

Reputation: 3579

You are checking is !isChecked so your code should be this

        if (!((Request["foo"] != null) && (Request["foo"].ToLower() == "on")))
        {
            // Do Stuff
        }

The not can be distributed and simplified by inverting all of the checks and the &&

        if ((Request["foo"] == null) || (Request["foo"].ToLower() != "on"))
        {
            // Do Stuff
        }

Upvotes: 1

Peter
Peter

Reputation: 27944

You do !isChecked, which is different as what you test. Try this:

 if(Request["foo"] != null && !(Request["foo"].ToLower() == "on"))

Upvotes: 1

Related Questions