4.2. if and if-else Statements

4.2.1. Simple if Statements

The if statement specifies a block of C# code to be executed if a condition is True.

Syntax of an if statement
if (condition)
{
  // block of code to be executed if the condition is True
}

Note

Note that C# is case sensitive, so If is not the same as if. “If” or “IF” will generate an error.

In if statements, the comparison operators [1] (>, <, >=, <=, ==, and !=) are used to evaluate the comparison expressions to derive a value of either true or false from the Boolean expression.

The first step to learn about the if statements is to perform some tests on the operators in csharprepl such as:

if (20 > 10)
{
   Console.WriteLine("20 is greater than 10");
}

with the output:

20 is greater than 10

When coding, we often play with variables rather than simple values. Observe the following code and test it in csharprepl to practice if statements with variables:

int num1 = 20;
int num2 = 18;
if (num1 > num2)
{
   Console.WriteLine("num1 is greater than num2");
}

Consider simple arithmetic comparisons that directly translate from math into C#. In csharprepl, enter:

int num = 11;

Now think of which of these expressions below are true and which false, and then enter each one into your csharp session to test:

2 < 5
3 > 7
num > 10
2*x < num

You see that the expressions evaluate to either true or false. These are the only possible Boolean values.

Run the example program below. Try it at least twice, with inputs: 30 and then 55. As you can see, you get different results, depending on the input. The main code is:

 1namespace IntroCSCS
 2
 3   class Chapter04
 4   {
 5      static void Main(string[] args)
 6      {
 7         Weight();
 8      }
 9
10      public static void Weight()
11      {
12         Console.Write("How many pounds does your suitcase weigh? ");
13         double weight = double.Parse(Console.ReadLine());
14         if (weight > 50)
15         {
16            Console.WriteLine("There is a $25 charge for luggage that heavy.");
17         }
18         Console.WriteLine("Thank you for your business.");
19      }
20
21}

In this code,

  • #7: The Main() method in the Chapter04 class called the Weight() method.

  • #14: the if statement in the Weight() method test the condition inside the parentheses.

  • If the condition is true that the weight is greater than 50, then the code block #15-17 would run, printing that there will be a $25 charge.

  • #18: No matter whether the if statement (#14-17) runs or not, print the “thank you” message.

You can see from this code that:

  1. The general C# syntax for a simple if statement is:

    if (condition)
    {
       // statement(s)
    }
    
  2. If the condition is true, then execute the statement(s) in braces. If the condition is not true, then skip the statements in braces.

  3. The condition is an expression that evaluates to either true or false, of type-boolean.

  4. An if statement only affects the normal sequential order inside the if statement itself (e.g., skipping the extra charge block when the condition is not true and still print the “thank you” line.

Another code fragment of banking account transaction as an example:

if (balance < 0)
{
   transfer = -balance;
   // transfer enough from the backup account:
   backupAccount = backupAccount - transfer;
   balance = balance + transfer;
}

The assumption in the example above is that if an account goes negative, it is brought back to 0 by transferring money from a backup account. Note that rhe choice is between doing something (if the condition is true) or nothing (if the condition is false). Often there is a choice of two possibilities, only one of which will be done, depending on the truth of a condition.

4.2.2. if-else Statements: Two-Way Selection

Since we can usually start analyzing a problem by coming up with two possibilities, it makes sense to add the alternative action to the code, which makes the if-else statements.

The general C# if-else syntax is:

if ( condition ) {
statement(s) for if-true
}
else {
statement(s) for if-false
}

Let us start by running the following example code (Clothes() method in Chapter04.cs). Try it at least twice, with inputs 50 and then 80. As you can see, you get different results, depending on the input.

namespace IntroCSCS
{

   class Chapter04
   {
      static void Main(string[] args)
      {
         // Rolla();
         // Weight();
         Clothes();
      }

      public static void Clothes()
      {
         Console.Write("What is the temperature? ");
         double temperature = double.Parse(Console.ReadLine());
         if (temperature > 70)
         {
            Console.WriteLine("Wear shorts.");
         }
         else
         {
            Console.WriteLine("Wear long pants.");
         }
         Console.WriteLine("Get some exercise outside.");
      }
   }
}

Note

You may see a warning in VS Code and when running the code as “warning CS8604: Possible null reference argument for parameter ‘s’ in ‘double double.Parse(string s)’.” You can safely disregard the warning message. For more information, see C# language reference. Basically, C# compiler produces warning at that line because argument of Parse is marked as “non-nullable” and the compiler determined that the parameter input you are passing to that call can be null at the point of call.

After running the code, you see that the if-else statement allows you to choose which of the two code paths to follow based on a Boolean expression. In an if-else statement, an if statement is followed by an else statement that is only executed when the original if condition is false. Note that in an if-else statement, exactly one of two possible code blocks in braces is executed.

A final print line is also shown that is not indented, about getting exercise. The if and else clauses each only embed a single (possibly compound) statement as option, so the last statement is not part of the if-else statement. It is beyond the if-else statement. It is just a part of the normal sequential flow of statements and therefore will be executed as part of the flow.