Chapter 2. Expressions and Control Structures

IN THIS CHAPTER

At the core of every language is the ability to perform two different types of tasks: repetition and conditional logic. Repetition involves using language constructs called loops to perform the same task multiple times. Conditional logic involves writing code that will only execute certain code based on specified conditions. This chapter introduces you to the basics of how to accomplish both of these types of tasks using the C# language.

If you have any familiarity with programming languages at all, the concepts discussed in this chapter should seem familiar and will be easy for you to pick up the C# syntax. If you have already been using C# for some time, you should be able to skim this chapter briefly as a refresher before continuing on through the rest of the book.

Branching and Conditional Logic

Every modern programming language supports the notion of branching and conditional logic. This gives your applications the ability to do different things based on current input, events, error conditions, or any condition that can be expressed logically. This section first shows you how C# allows you to form logical expressions and how to create code blocks that are executed conditionally based on those expressions. Then you’ll see a couple of shortcuts and extras that C# contains to make using certain types of common logic statements even easier.

Introduction to Boolean Expressions

A Boolean expression is a code statement that will eventually evaluate to either true or false. At the most basic level, all Boolean expressions, no matter how long or complex, are still going to evaluate to either true or false.

The simplest of all Boolean expressions is equality. This expression is used to test whether or not one value is equivalent to another value. This can be something simple, such as

2 == 4

This expression will evaluate to false because 2 is not equal to 4. It can also be something complex, such as

MyObject.MyProperty == YourObject.YourProperty

This expression could evaluate to anything, and would be determined at runtime. If you are familiar with C, C++, or even C#, you know that the == (double-equals) is a logical Boolean operator, and the = (single equals) is an assignment operator used to set values. A common source of runtime and compile-time errors revolves around using these operators in the wrong place.

Table 2.1 shows the logical operators available in the C# language and provides a brief description of their purpose.

Table 2.1 C# Logical Operators

Image

Using Basic Conditional Statements

In the preceding section you were introduced to the tools you need in order to form Boolean expressions. These will allow you to assert whether or not an expression is true. When you have such an assertion, you need to be able to provide some conditional statements in your code to allow you to do something meaningful based on the results of a Boolean expression. This section will show you the basic conditional statements that are at the heart of almost all logic code in C#.

Using If/Else Statements

The format of an if statement is as follows:

if ( expression )
   code_block
else if ( expression_1 )
   code_block
else if ( expression_2 )
   code_block
else
   code_block

Both the else if and else sections are optional, and are only required if you want your code to perform alternate tasks when the original Boolean expression evaluates to false.

Because each of the code blocks in the preceding example can also contain their own if statements, you can nest your conditional code nearly as deep as you like. However, good style and etiquette recommend that you avoid deep nesting because it makes your code difficult to read and analyze.

The following sample if statements illustrate using if simply, nested, and with else statements:

Image

Using the Switch Statement

If you want to test a single variable against a list of possible values using just the standard if/else keywords, you will end up with code that looks like the following:

Image

Although this may get the job done, it’s not the most elegant or the most easily readable block of code. For this situation, C# has the switch statement, which allows you to combine several logic tests into a single expression, as shown in the following example:

Image

Using the Goto Statement

The goto statement has two main uses; one is to transfer control from one case within a switch statement, and the other is to break out of loops. You will see more on loops later in this chapter.

The following is a sample of a switch statement that utilizes the goto keyword for transferring control:

Image

Using Advanced Conditional Statements

One of the most common uses for an if/else statement is to conditionally print something or render something through Windows Forms or Web Forms. For example, suppose that you want to print the word “Good” if the profit margin is greater than 20, or “Bad” if the profit margin is less than or equal to 20. You might use an if/else that looks like the following:

Image

This is perfectly fine, but C# includes a ternary operator called the conditional operator that allows you to embed an if/else combination in a single line. You can rewrite the preceding code segment in a single line as follows:

Console.WriteLine("The profit margin is " + (profitMargin > 20) ? "Good" : "Bad");

The ternary conditional operator has the following format:

expression ? return_when_true : return_when_false

Looping and Repetition

In addition to conditional logic and branching, looping is one of the most common tasks performed by all applications, regardless of the application type. It is impossible to find a production-quality application written in .NET today that does not include some use of loops.

A loop is a repetition of a code block a certain number of times. The number of times is determined by the type of loop being used. This section will show you the basics of creating and using loops in C#.

Using the for Loop

Each for loop has three sections:

  1. The initializer. This is a block of code that is executed once at the beginning of the for loop. Variables declared in this section are available for the scope and duration of the loop but will not remain outside the loop. This section is typically used to initialize the counter variable or variables.
  2. The exit condition. This section defines a Boolean expression that is used to determine how long the for loop keeps running. As long as the Boolean expression continues to evaluate to true, the loop keeps running. This expression is tested at the beginning of each loop execution.
  3. The iterative code. This section is arbitrary, and can contain any code that you want to execute at the end of each iteration through the loop. This is typically where the loop counter variables are incremented.

The format of the for loop is as follows:

Image

So, to create a for loop that will execute a block of code five times, you would write the following:

for (int x = 0; x < 5; x ++) 
      Console.WriteLine("The value is " + x.ToString() );

This will print the following output:

0
1
2
3
4

Using the while Loop

Whereas the for loop is typically used to provide an indexed (a counter variable) loop, the while loop will continually perform the same action over and over again so long as a given Boolean expression evaluates to true. The format of this loop is as follows:

while ( expression ) { ... }

If you wanted to perform an action until some flag indicated that you could not perform it any more, your while loop might look something like the following:

Image

The expression is evaluated at the beginning of each loop execution, and if the evaluation is false, the code within the loop will not be executed. A common mistake when using while loops is neglecting to set the exit condition for the loop. In the preceding example, this is the canContinue variable. If you don’t set the exit condition for the while loop, it will run forever (or until you shut the application down forcefully).

Using the do Loop

The do loop is similar to the while loop, except that the Boolean expression is evaluated at the end of the loop execution instead of at the beginning of the loop. The format of the do loop is as follows:

do
{
        ...
} while ( expression );

The use of the do loop always guarantees that the code inside the loop will execute at least once. All the other loop types have the ability to execute 0 times if the entry condition fails. Here is a sample do loop:

Image

Summary

Whether you’re working with a database, 3D graphics, a console application, a Windows Forms application, or a Web Forms application, there are a few types of tasks that need to be performed: looping and branching.

Looping and branching are at the core of any language’s definition. This chapter has shown you how you can use C# to create complex branching using Boolean expressions as well as multiple ways to perform iterative programming tasks by using loops.

This chapter has presented some information that, on its own, may not appear to be entirely useful. However, when you look at virtually every programming problem you will ever face in the future, you will be hard-pressed to find a scenario that does not involve looping and branching in some respect.

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

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