Beginning C#: Making Decisions

Last month, we looked at variables in more detail. This month, we're going to learn how to use the data you've got stored in the variables to allow your programs to make decisions.

Decisions in C# are quite simple to do and involve the well-known "if", "then", "else" structure that most languages have.

An if statement is known as a "truthy" statement. What this means is that it doesn't actually pass or fail based on the condition of its operators, but rather it passes or fails depending on the operation on its operands producing a true or a false result.

I realise that the previous paragraph may not make much sense (it didn't when I first learned to program), but bear with me. I'll explain what it means.

Computers are not inherently able to know how similar something is to something else, and so cannot answer something like:

"Dark Brown is similar to Light Brown."

What they can do, and do very fast, is to say that something is not equal. So, taking the previous statement, a computer can say that:

"Dark Brown is absolutely not equal to Light Brown."

Showing this as a "truthy" statement means we can definitely say:

"It's TRUE that Dark Brown is absolutely not equal to Light Brown."

Or

"Its FALSE that Dark Brown is absolutely equal to Light Brown."

Note the "TRUE" and "FALSE" here. It's not the response to the comparison we're interested in; it's what we can determine about the comparison that's the interesting part.

Taking a more classic comparison:

"is Name equal to 'Peter'"

If the variable called Name contains 'Peter', then from a truthy point of view

"it's TRUE that the variable Name is equal to 'Peter'"

Again, it's not the comparison that matters; it's the fact that the operation of comparing the contents of the variable called Name to the string 'Peter' yields us a TRUE result.

Practice it a few times, and it'll start to make sense.

If we start to put this into an actual if/then statement, you'll also start to understand it better.

Start a console mode program, and add the following code to your main program.

using System;

namespace NutsAndBolts
{
   class Program
   {
      static void Main()
      {
         string Name = "Peter";

         if(Name == "Peter")
         {
            Console.WriteLine("Your name is peter");
         }


      }
   }
}

The if statement, as you can see, is using '==' as its operation. '==' means "Is Equal to" and is used to perform an equality operation between the two operands, in this case the contents of the variable 'Name' and the string "Peter".

If you observe, the 'if' statement operation is enclosed in standard brackets, and this strengthens the fact that the result of anything inside those brackets should give either TRUE or FALSE as its result.

If you run the program, you should see the following:

Decision
Figure 1: Output from our first if statement

You also can check if something is the inverse by using the "Is NOT Equal to" operation, which looks like this:

using System;

namespace NutsAndBolts
{
   class Program
   {
      static void Main()
      {
         string Name = "Peter";

         if(Name != "Peter")
         {
            Console.WriteLine("Your name is not peter");
         }

      }
   }
}

The exclamation mark negates the operation to be the opposite of what it would normally be.

If you're comparing numbers, you can make other decisions too, such as "Is greater than" which is represented by '>' and "is less than", represented by '<'. These are used as follows:

using System;

namespace NutsAndBolts
{
   class Program
   {
      static void Main()
      {
         int Number = 30;

         if(Number > 20)
         {
            Console.WriteLine("Number is larger than 20");
         }

         if(Number < 50)
         {
            Console.WriteLine("Number is smaller than 50");
         }

      }
   }
}

Understanding the "Truthy" nature of an if statement is very important once you start dealing with equations. Each side of the operation doesn't have to be a single variable or a static value; you can include complex math equations in there if you wish, too; for example:

using System;

namespace NutsAndBolts
{
   class Program
   {
      static void Main()
      {
         int Number = 30;

         if(((Number * 10) / 15) > ((Number * 15) / 20))
         {
            Console.WriteLine("I'm not even going to try and work that one out :-)");
         }

      }
   }
}

Is perfectly valid, and, as you can see, very self-contained on each side of the operation.

There's also a second part to the if statement, and that's the "else" part. The "else" part contains the code to execute if the original decision doesn't resolve to a "TRUE" condition. For example:

using System;

namespace NutsAndBolts
{
   class Program
   {
      static void Main()
      {
         string Name = "Peter";

         if(Name == "Peter")
         {
            Console.WriteLine("Your name is peter");
         }
         else
         {
            Console.WriteLine("Your name is not peter");
         }
      }
   }
}

If you compile and run this version, and change the 'string Name = ' line, you should be able to get the decision logic to switch between the two cases.

To finish off this month's post, I encourage you to go back and recap the previous posts, and put together a small program that uses 'ReadLine' to read in a name, and then print different messages depending on different tests. Next month, we look at 'if' in more detail, where I'll explain how to use different operators to combine several tests into one decision, using Boolean logic.



About the Author

Peter Shaw

As an early adopter of IT back in the late 1970s to early 1980s, I started out with a humble little 1KB Sinclair ZX81 home computer. Within a very short space of time, this small 1KB machine became a 16KB Tandy TRS-80, followed by an Acorn Electron and, eventually, after going through many other different machines, a 4MB, ARM-powered Acorn A5000. After leaving school and getting involved with DOS-based PCs, I went on to train in many different disciplines in the computer networking and communications industries. After returning to university in the mid-1990s and gaining a Bachelor of Science in Computing for Industry, I now run my own consulting business in the northeast of England called Digital Solutions Computer Software, Ltd. I advise clients at both a hardware and software level in many different IT disciplines, covering a wide range of domain-specific knowledge—from mobile communications and networks right through to geographic information systems and banking and finance.

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date