Chapter 4. Using Methods and Exceptions

In This Chapter

Introducing methods

Pondering some good reasons to use methods in your programs

Creating methods that return values

Creating methods that accept parameters

Dealing with exceptions

In C#, a method is a block of statements that has a name and can be executed by calling (also called invoking) it from some other place in your program. If you’ve coded some of the examples in this mini-book, then you’re already experienced with using methods; when you use Response.Write to write data to the page (for example), you’re calling a method.

In addition, the code that responds to events such as button clicks is written in methods. Besides such event-handling methods, you can put other methods in the code-behind file to handle other tasks. This chapter shows how.

Another important aspect of C# programming is working with exceptions — those pesky times when the program (like the universe) balks at following the rules you’ve so carefully created. This chapter covers that important detail as well.

The Basics of Making Methods

All methods must begin with a method declaration, a statement that identifies the method for the program. Here’s the basic form for a method declaration, at least for the types of methods I talk about in this chapter:

protected return-type method-name (parameter-list)
{
        statements...
}

Here’s a rundown of the parts that make up a method declaration, defined piece by piece:

  • protected: This keyword indicates that the method’s existence ...

Get ASP.NET 2.0 All-In-One Desk Reference For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.