Reusing Code with Methods
Sometimes a program needs to perform the same action in several places. For example, suppose
youre using a simple editor such as WordPad, you make some changes, and then you select the
File menu’s New command. The program realizes that you have unsaved changes and asks if
you want to save them. Depending on whether you click Yes, No, or Cancel, the program saves
the changes, discards the changes, or cancels the attempt to create a new file.
Now think about what happens when you try to open a file while you have unsaved changes.
The program goes through basically the same steps, asking if you want to save the changes. It
does practically the same thing if you select the File menus Exit command, or click the X in
the programs upper-right corner, or open the windows system menu and select Close, or press
[Alt]+F4. In all of these cases, the program performs basically the same checks.
Instead of repeating code to handle unsaved changes everywhere it might be needed, it would
be nice if you could centralize the code in a single location and then invoke that code when
you need it. In fact, you can do exactly that by using methods.
A method is a group of programming statements wrapped in a neat package so you can
invoke it as needed. A method can take parameters that the calling code can use to give it
information, it can perform some actions, and then it can return a single value to pass infor-
mation back to the calling code.
In this lesson, you learn how to use methods. You learn why they are useful, how to write
them, and how to call them from other pieces of code.
METHOD ADVANTAGES
The file editing scenario described in the previous section illustrates one of the key advan-
tages to methods: code reuse. By placing commonly needed code in a single method, you
can reuse that code in many places. Clearly that saves you the effort of writing the code
several times.
20
596906c20.indd 241 4/7/10 12:33:27 PM

Get Stephens' C# Programming with Visual Studio® 2010 24-Hour Trainer 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.