Using Blocks of Code


Another key element of C# is the code block. A code block is a grouping of two or more statements. This is done by enclosing the statements between opening and closing curly braces. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be a target for if and for statements. Consider this if statement:

 if(w < h) {   v = w * h;   w = 0; }

Here, if w is less than h, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and one statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block. Code blocks allow many algorithms to be implemented with greater clarity and efficiency.

Here is a program that uses a block of code to prevent a division by zero:

 // Demonstrate a block of code. using System; class BlockDemo {   public static void Main() {     int i, j, d;     i = 5;     j = 10;     // the target of this if is a block     if(i != 0) {       Console.WriteLine("i does not equal zero");       d = j / i;       Console.WriteLine("j / i is " + d);     }   } }

The output generated by this program is shown here:

 i does not equal zero j / i is 2

In this case, the target of the if statement is a block of code and not just a single statement. If the condition controlling the if is true (as it is in this case), the three statements inside the block will be executed. (Try setting i to zero and observe the result.)

Here is another example. It uses a block of code to compute the sum and the product of the numbers from 1 to 10.

 // Compute the sum and product of the numbers from 1 to 10. using System; class ProdSum {   public static void Main() {     int prod;     int sum;     int i;     sum = 0;     prod = 1;     for(i=1; i <= 10; i++) {       sum = sum + i;       prod = prod * i;     }     Console.WriteLine("Sum is " + sum);     Console.WriteLine("Product is " + prod);   } }

The output is shown here:

 Sum is 55 Product is 3628800

Here, the block enables one loop to compute both the sum and the product. Without the use of the block, two separate for loops would have been required.

One last point: Code blocks do not introduce any runtime inefficiencies. In other words, the { and } do not consume any extra time during the execution of a program. In fact, because of their ability to simplify the coding of certain algorithms, the use of code blocks generally increases speed and efficiency.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net