Conditional programming in C#

Conditional statements are used so that your program can make decisions based on different conditions. For example, a game might display a message to the player if their score is higher than a certain number. Or an app might provide different content based on its user’s age. When your program has a range of conditions, you can build powerful algorithms.

Watch the video below and then scroll down to view the sample code.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
   Console.WriteLine("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if statements allow you to specify what action will occur when a condition is met and else statements can be used to run another piece of code if the condition is not met. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else
{
   Console.WriteLine("You are not old enough to vote");
}

else if statement

The limitation of using just if and else statements is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the else if statement comes in.

Using else if statements allows you to test multiple conditions. You can have several else if statements that each test a different condition. The else part is optional when using if and else if statements but is handy if you want something to happen if none of the specified conditions are met.

Here is some sample code for the ifelse if and else statements:

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else if(age==17)
{
   Console.WriteLine("You can vote after your next birthday");
}
else
{
   Console.Writeline("You are not old enough to vote");
}

Sample C# code

Here is the sample C# code used in the video. Comments have been added to the code to explain each part of the code.

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      // Ask the user to select an option (type of calculation)
      // \n will create a new line
      Console.WriteLine ("Select from one of the following options: \n1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");

      // Store the selected option in a variable as an integer value (1, 2, 3, or 4)
      int option = int.Parse (Console.ReadLine ());

      // Ask the user to enter two numbers
      Console.WriteLine ("Enter two numbers...");

      // Store the first number in a variable as a float value
      float num1 = float.Parse(Console.ReadLine ());

      // Ask the user to enter the first of the two numbers
      Console.WriteLine ("Enter the first number:");

      // Ask the user to enter the second of the two numbers
      Console.WriteLine ("Enter the second number:");

      // Store the second number in a variable as a float value
      float num2 = float.Parse(Console.ReadLine ());

      // check the option selected and display the result of the relevant calculation

      // if option 1 (add) was selected...
      if (option == 1) {
        Console.WriteLine ("The answer is: " + (num1 + num2));
      }

      // if option 2 (subtract) was selected...
      else if (option == 2) {
        Console.WriteLine ("The answer is: " + (num1 - num2));
      }

      // if option 3 (multiply) was selected...
      else if (option == 3) {
        Console.WriteLine ("The answer is: " + (num1 * num2));
      }

      // if option 4 (divide) was selected...
      else if (option == 4) {
        Console.WriteLine ("The answer is: " + (num1 / num2));
      } 

      // if no option was selected...
      else {
        Console.WriteLine ("Option is not recognised");
      }
    }
  }
}

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Logical operators

Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s firstname is “Joe” AND their last name is also “Bloggs”.

if (first_name == "Joe" && last_name == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Next tutorial: While loops in C#