Lesson 2.2.5 Conditions

I alluded earlier to the point that C# has the ability to offer more sophisticated and beefy condition specifications. Some might have spotted that the conditions I have specified so far in examples only check for one thing. Going back to real life, an “if” will come attached with all kinds of attached provisos.

“If the soup is a bit bland and not already salty, add salt”

“If they have that cheese that I like and it’s still on offer, pick me some up at the supermarket”

“If they try to charge you too much or they’re not any good, forget the olives”

The above conditions are a little more involved are they not? They depend on more than one thing. C# helps to mimic by using the two words that we could not operate without. They are OR and AND. These humble monosyllabic words are basically what all computer systems hinge on. In elementary electronics in school you may have been introduced to the OR gate, AND gate or one of their cousins, NOR, NAND, XOR etc. This kind of logic is wired into the very being of the machine.

An example of the code using these techniques is shown below. This shows the use of both an AND and an OR.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConditionalLogic
{
    class Program
    {
        static void Main(string[] args)
        {
            if (DateTime.Now.Day < 15 && DateTime.Now.Minute < 15)
            {
                System.Console.WriteLine
                    ("It's first half of the minute and the month");
            }
            if (DateTime.Now.Day == 1 || DateTime.Now.Second == 1)
            {
                System.Console.WriteLine
                    ("It's either the start of the month or the minute");
            }
            System.Console.ReadKey(true);

        }
    }
}

The first “if” statement uses an AND.

  if (DateTime.Now.Day < 15 && DateTime.Now.Minute < 15)

It checks to see if the day of the month is less than fifteen and the minute is less than 15. As you can see, the actual word “and” has been replaced by the two ampersand symbols. That’s it.

The next “if” statement uses an OR.

  if (DateTime.Now.Day == 1 || DateTime.Now.Second == 1)

This uses two pipe symbols to represent an OR. The pipe symbol is the one next to the Z key. Hopefully, that should be undemanding to understand.

But there are is one important nuance to grasp. It is called conditional precedence. Anything involving money can give us an insight; tax is a good example.

“If the person has earned over £6000 this year or has no tax code and is not dead they must pay tax”

I’m going to put on my pedant’s hat and point out the grammatical ambiguities in that sentence. If you take the “or” and the “and” in the wrong order it could mean you still have to pay taxes if you’re dead! Look at the text for a moment and you will see what I am getting at. It simply depends on whether you look at the “and” part of the logic first or the “or”.

It rather raises the question, let’s suppose an equivalent question was asked in C#. Using my hybrid C#/English notation it could look like this.

  if (pay > 6000 || no tax code && is not dead)
  {
      System.Console.WriteLine("Must pay tax");
  }
  else
  {
      System.Console.WriteLine("Tax exempt");
  }

I can tell you that C# would tell the person to pay taxes if they were dead. This is for one simple reason. In C#, AND operations are worked out before OR operations. It’s such a piffling point that if you didn’t know about it you might stay sat there looking at the code until your forehead bled. Being aware of it may well save your sanity.

So, is there are a way around it? After all, rearranging the order of the condition isn’t going to help. We’ve just established it doesn’t matter what order they’re in because AND logic is worked out first. The answer is brackets.

  if ((pay > 6000 || no tax code) && is not dead)
  {
      System.Console.WriteLine("Must pay tax");
  }
  else
  {
      System.Console.WriteLine("Tax exempt");
  }

Just as in maths, what’s in the brackets is done first, so it is in conditional logic. We are forcing C# to work out the OR logic before the AND logic. We get our own way.

This is what computers understand. Computers don’t really deal in fuzzy decisions in the same way as humans. Humans can make judgement calls and intervene with common sense. Computers don’t, they are frustratingly pedantic and can drive you up the wall with the way they follow you to the letter. This could be a reason why some coder geeks can derive great pleasure from correcting other humans, why not? They do it to computers all day.


Supporting files

File Description Open with
Conditional logic project Contains the console project from the lesson Visual C# 2008