9.1. The if Statement

The if statement is a control statement that executes a block of code if an expression evaluates to true. It takes this form:

if (expression)
  statement1
else
  statement2

where

  • expression is an expression that can be implicitly converted to bool or a type that contains overloading of the true and false operators

  • statement1 is the embedded statement(s) to be executed if expression is true

  • statement2 is the embedded statement(s) to be executed if expression is false

Note that unlike C++, C# and Java do not allow the expression to be evaluated to 1 or 0. That is, the integer 1 does not stand for true, and 0 does not stand for false.

If expression is true, then statement1 is executed. If the optional else clause exists and expression evaluates to false, then statement2 is executed. After the if statement is executed, control is transferred to the next statement.

You can conditionally execute multiple statements by including them in a block following an if expression. The statement(s) to be executed upon testing the condition can be of any kind, including another if statement nested into the original if statement. In nested if statements, the else clause belongs to the last if that does not have a corresponding else. Here is a nested if statement:

if (x > 10)
  if (y > 20)
    Console.Write("Statement_1");
  else
    Console.Write("Statement_2");

In this example, Statement_2 will be displayed if the condition (x > 10) evaluates to true and the condition (y > 20) evaluates to false. However, if you want to associate Statement_2 with the condition (x >10), you use braces:

if (x > 10)
{
  if (y > 20)
    Console.Write("Statement_1");
}
else
    Console.Write("Statement_2");

In this case, Statement_2 will be displayed if the condition (x > 10) evaluates to false.

Listing 9.1 shows the conditional if constructs in action. Like Java, C# supports the if, if-elseif, if-elseif-else, and if-else constructs. The condition that is to be evaluated must be of type bool, a requirement that is similar to Java's requirement of having the condition as a Boolean. C# also supports short-circuiting. Upon running Listing 9.1 and passing 10 as the command line argument, you get the following output:

First if
First else-if
Second else-if
No short circuit. I am 11
I did short circuit, I am still 11

In Listing 9.1 the value of i is not incremented the second time; it stays at 4 because C# short-circuits the evaluation of if (true || ++i > 0) and evaluates only if (true).

Listing 9.1. The if Statement Constructs (C#)
using System;

public class Test {

  public static void Main(string[] args) {

    //Ignore exceptions for now.
    int i = Int32.Parse(args[0]);
    //if-statement
    if (i > 0) {
      Console.WriteLine("First if");
    };
    //if-elseif statement
    if (i <=0 ) {
      Console.WriteLine("Second if");
    } else if (i > 0) {
      Console.WriteLine("First else-if");
    }
    //if-elseif-else
    if (i < 0 ) {
      Console.WriteLine("Third if");
    } else if (i > 0) {
      Console.WriteLine("Second else-if");
    } else {
      Console.WriteLine("First else-if");
    }
    //Short-circuiting in action
    if (++i > 0) {
      Console.WriteLine("No short circuit. I am "+i);
    }
    if (true || ++i > 0) {
      Console.WriteLine("I did short circuit, I am still "+i);
    }

    }
}

If the condition inside the if construct evaluates to true, then the statements corresponding to that construct are executed. Well, almost always—except for special cases such as shown in Listing 9.2.

Listing 9.2. Taxing the CLR (C#)
using System;

public class Test {

  static int limit = 0;
  public static void Main(string[] args) {
    try {
      recurse();
    } catch (StackOverflowException e) {
      Console.WriteLine("OK OK, the CLR has its limits");
    } finally {
      Console.WriteLine("Final limit "+limit);
    }
  }

  static public bool recurse() {
    ++limit;
    if (recurse()) {
      Console.WriteLine("true");
    }
    return true;
  }
}

Listing 9.2 is interesting because of the special case of recursion; we have a situation in which the statement true never gets printed during program execution. Running Listing 9.2 gives a StackOverflowException, which is an exception that is thrown when there are too many nested method calls. Ideally, you would wrap the call to recurse() in a try-catch-finally block (see Chapter 10) so as to end the program more elegantly.

Scoping of variables for the if construct follows the same rules as in Java. As shown in Listing 9.3, the variable methodlocal is available both in the if and in the else construct. The variable iflocal is available only in the if construct, and its nested constructs and the elselocal variable are available only in the else construct and its nested constructs.

Listing 9.3. Scoping of Variables in the if Constructs (C#)
using System;

public class Test {

  public static void Main(string[] args) {
    int methodlocal = 2;
    if (false) {
      int iflocal = 3;
      if (!false) {
        Console.WriteLine(methodlocal*iflocal);
      }
      Console.WriteLine(+  ethodlocal);
    } else {
      int elselocal = 3;
      if (!false) {
        Console.WriteLine(methodlocal*elselocal);
      }
      Console.WriteLine(—methodlocal);
    }
  }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.92