Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Visual CSharp 2005 Express Edition (2006) [eng]

.pdf
Скачиваний:
42
Добавлен:
16.08.2013
Размер:
9.96 Mб
Скачать

Chapter 6

Breaking on Exceptions. This option enables you to specify which errors (exceptions) you want to have your system break on. Exceptions are runtime errors that you can’t necessarily debug and remove from your applications. However, you can “catch” the errors and handle them. Sometimes you will purposely want your exceptions to break your applications when you are debugging them, so you can figure out how to handle them. You can get to the Exception feature by choosing Debugging Exceptions. When chosen, you will then see the Exceptions dialog box displayed in Figure 6-12.

Figure 6-12

Exceptions are discussed in Chapter 7.

Data Visualizers. A new feature in C# Express, Data Visualizers let you visualize your data when in debugging mode. This is very cool because it enables you to work though data as you would other variables in your application.

Summar y

In this chapter, you have seen that there are many ways to debug your applications. Some of the syntactical errors are caught when you are trying to build your applications, using the Error List by doubleclicking the error, and having the editor take you to the exact piece of code that is causing the errors. As you are fixing errors, you will notice that sometimes when you fix one error, you uncover a number of others.

There are some errors you can correct when you walk line by line through the code and examine the data. C# Express provides many tools to make the job easier using breakpoints, Watch windows, and the new Edit and Continue feature. Breakpoints give you the ability to stop the execution of your application just about anywhere in your code. You can even disable a breakpoint while leaving it in the code for later use.

94

Debugging Applications in C# Express

By debugging your application thoroughly and adding exceptions, as described in Chapter 7, you can make your applications pretty darned bulletproof. This chapter showed you how to use the various tools in C# Express to debug your applications. As mentioned, don’t sweat it if you are a little confused or nervous with some other tools presented in this chapter. It is a big tool chest, but just like in real life, you start with the easy tools like a hammer or screwdriver, get comfortable with those, then move onto the jigsaws and routers (whatever those are).

Exercises

1.Name the two different types of errors you can debug.

2.What are some of the ways to work with breakpoints?

3.Name two of the windows that are used for displaying values in break mode.

4.What is the technology that enables you to hover the mouse over variables and see their values in break mode?

5.What are the three commands for stepping through code?

95

7

Selections, Iterations, and

Catching Exceptions

In living your day-to-day life, you have to make decisions. I remember when I graduated from high school I didn’t really want to make any decisions, but alas, such is life. It can also be said that when programming your applications, regardless of what language you are using, you will have to make decisions in the code. In both code and life, once decisions are made, you will take one action or another. In coding, this decision making is called selection, also known as branching. When you need to make decisions and branch, C# provides a number of statements, such as if . . .

else and switch, that can help you compare variables and objects in your code and execute blocks of code based on decisions made.

Another necessary feature of the programming language is to perform loops, also referred to as iterations. Examples of iterations are when you want to have your code loop through the days of a given month and perform an action for each day, or just do a count up to 10. You need to be able to tell your application to perform a code block for a specified number of times. C# provides a number of statements for accomplish iterations depending on what the task is.

Lastly, no matter how well you build your code, issues are going to occur. These issues, called exceptions in the .NET realm, can cause serious problems if not handled correctly. How you handle these exceptions affects the overall user experience in working with your applications (and also could spare you from getting beat up by IT people).

In discussing the topics just mentioned, this chapter will cover:

Calling routines from one another

Working with if . . . else statements to handle simple conditional selection

Using switch statements for more complex selections

Working with for statements to accomplish iterations

Learning how to use try . . catch . . finally to catch exceptions that can occur

Chapter 7

Performing Selections in Your Applications

While not every routine you create in C# will require you to make decisions and select either a single line or blocks of code, it happens quite frequently. It would be very limiting if C# didn’t offer commands that take the need to branch in your code into consideration. The majority of programming languages offer some kind of branching statements as far back as some of the original machine languages.

C# has two main statements to facilitate selection in C#: if . . . else for simple branching and switch . . . case for more complex selections. Before jumping into the statements, I want to discuss the project used for these examples and have you create it.

Creating the Chapter 7 Project

To show this and the other examples in this chapter, you will create a form that can be used to display results from all the examples. The form is shown in Figure 7-1.

Figure 7-1

As you can see from the number of buttons displayed here, there is a lot of work to do. So get started already!

Try It Out

Create the Sample Form

To help you understand how to use the various statements discussed in this chapter, besides the buttons used for executing the examples that most of the forms in the book use, you will add two Label and two TextBox controls. You will use the first text box to input values, and when you click each of the buttons, the code will display values in the second text box.

1.

2.

Open C# Express.

Click New Project.

98

Selections, Iterations, and Catching Exceptions

3.Choose Windows Application for the template to use.

4.Name the project, and click OK. The project is created and the default form displayed.

I will leave it up to you to specify the properties of the form and command buttons as you see fit, since the purpose of this chapter is to focus on statements, and you have had a lot of experience creating simple forms.

5.Add the two Label controls and specify the Text property in the Properties window to display “First Text Box” and “Second Text Box”.

6.Add the two TextBox controls below each Label control added. Make sure that the Name properties of the two controls are textBox1 and textBox2, which should be the default setting.

7.Set the Multiline property of each TextBox control to True, as shown in Figure 7-2 for textBox1. The figure also shows how the four controls described in these steps could look.

Figure 7-2

Okay, now you’re ready to get into the various statements I wanted to discuss in this chapter.

Simple Selection Using if...else Statements

When you have a quick decision to make in your code, if . . . else statements are the ones to use. The syntax for these statements is as follows:

99

Chapter 7

if (criteria true value) statement(s) to perform if true

else

statement(s) to perform if false

As I mentioned, you are making decisions in code and selecting a path (code) that you want to take, just like in real life.

One nice thing about the if statement is if you only want to execute a line of code if something is true, you don’t even have to use the else portion of the statements. This is shown in the following:

if (this.textBox1.Text == “Display”)

this.textBox2.Text = “I am displaying”;

This way, you perform the action only if the criteria in the if statement is met, in this case:

this.textBox1.Text == “Display”

You need to make sure you surround the criteria with parentheses (). Also, remember that by using the == you are performing a comparison, not assigning the value.

Working with Criteria

When dealing with criteria in various statements, you will have to remember your good old high school algebra. Actually, you will use what is called boolean algebra in comparisons.

Utilizing Operators

When looking at criteria, whenever you need to compare values such as the text box value with the literal string “Display”, you will use an operator. Operators provide the means for C# to perform boolean evaluations, meaning returning true or false. In this case == is used so see if two values are equal. There are a number of other operators that you can use, depending on the criteria you are trying to evaluate. Here is a table of some of the other operator possibilities:

Symbol

Description

 

 

==

Equal

>=

Greater than or equal to

>

Greater than

!=

Not equal to

<=

Less than or equal to

<

Less than

 

 

There are additional operators, but these are the most common and will get you started nicely. You will use operators with more than just selection-type statements. You will use them for iteration statements as well.

100

Selections, Iterations, and Catching Exceptions

For another example of using one of the other operators, if you wanted to look at a variable called intAge and make sure that code was only executed if the age was 18 or older, the selection line of code would look as follows:

if (intAge >= 18)

I think you get the idea. One last topic to discuss with regard to criteria is the use of complex criteria.

Complex Criteria

When you need to compare more than one value on a line, you will use additional operators that performs AND and OR logic. Below are some of those operators.

Symbol

Description

&&

Logical AND

||

Logical Or

Suppose you need to look not only at those who are 18 and over but also (AND) check that the value in strState is equal to “WA”. The selection line of code would be

if ((intAge >= 18) && (strState == “WA”))

Notice the use of parentheses; just as in algebra, you can control which operators get evaluated based on how you have the parentheses positioned. Those operators inside parentheses are evaluated first.

Using Code Blocks with Selection

Instead of single lines of code as shown previously, you can use code blocks surrounded by {}. Say in addition to updating the second TextBox control, you want to display a message box. This would be accomplished with the following lines of code:

if (this.textBox1.Text == “Display”)

{

this.textBox2.Text = “I am displaying”; MessageBox.Show(“Displaying here too”);

}

Time to go ahead and use the if statement.

Try It Out

Use an if Statement to Select a Block of Code

Using the form you created in the first Try It Out:

1.Drag and drop a Button control onto the form.

2.Name it as desired. For this example, the Button control was named btnIf.

101

Chapter 7

3.Double-click the btnIf button. The btnIf_Click routine is created as shown here:

private void btnIf_Click(object sender, EventArgs e)

{

}

4.With the cursor between the curly brackets, type the following lines of code:

if (this.textBox1.Text == “Display”)

{

this.textBox2.Text = “I am displaying”; MessageBox.Show(“Displaying here too”);

}

So the complete btnIf_Click event code looks as follows:

private void btnIf_Click(object sender, EventArgs e)

{

if (this.textBox1.Text == “Display”)

{

this.textBox2.Text = “I am displaying”; MessageBox.Show(“Displaying here too”);

}

}

5.Press F5 to build and execute the application.

6.Type Display into the first text box.

7.Click the Button control you added. The form (minus some of the buttons) and message box shown in Figure 7-3 appears.

Figure 7-3

102

Selections, Iterations, and Catching Exceptions

While this is great when you only want to perform actions when a value is true, you can also use an else statement to perform an alternate line or block of code.

Adding the else Statement

As mentioned, adding an else statement onto an if statements gives you the ability to perform more than one set of commands. To accomplish this, you place the else statement after the last statement executed for the if statement:

if (this.textBox1.Text == “Display”) this.textBox2.Text = “I am displaying”;

else

this.textBox2.Text = “I am not displaying”;

So you can see how easy it is to handle this type of situation.

Additional Ways to Use the if . . . else

In addition to using the else statements, there are a couple of other ways to control the selection of code:

Using if . . . else if . . . else. To make it even more complete, you can add if statements onto the else statements for even more control. The syntax for this would be as follows:

if (<criteria true value>) statement(s) to perform if true

else if (<criteria2 true value>)

statement(s) to perform if second criteria is true

else

statement(s) to perform if false

Nesting if...else statements. By nesting if . . . else statements, you can perform additional statements and control the flow of the code as necessary:

if (<criteria true value>) if (<criteria 2 true value>)

statement(s) to perform if true

else

statement(s) to perform if false

Try It Out

Use if . . else Statements to Select Code

Using the form you created for the chapter:

1.Drag and drop another Button control onto the form.

2.Name it as desired. For this example, the Button control was named btnIfElse.

3.Double-click the btnIfElse button. The btnIfElse_Click routine is created as shown here:

private void btnIfElse_Click(object sender, EventArgs e)

{

}

4.Type the following code between the curly brackets:

103

Соседние файлы в предмете Программирование на C++