All the code you have seen so far has taken the form of a single block, perhaps with some looping to repeat lines of code and branching to execute statements conditionally. If you've needed to perform an operation on your data, then this has meant placing the code required right where you want it to work.

This kind of code structure is limited. You will often find that some tasks, for example finding the highest value in an array, may need to be performed at several points in a program. You can just place identical (or near identical) sections of code in your application whenever necessary, but this has its own problems. Changing even one minor detail concerning a common task (to correct a code error, for example) may require changes to multiple sections of code, which may be spread throughout the application. Missing one of these could have dramatic consequences and cause the whole application to fail. In addition, the application could get very lengthy.

The solution to this problem is to use functions. Functions in C# are a means of providing blocks of code that can be executed at any point in an application.

Functions of the specific type examined in this chapter are known as methods. However, this term has a very specific meaning in .NET programming that will only become clear later in this book, so for now this term will not be used.

For example, you could have a function that calculates the maximum value in an array. You can use this function from any point ...

Get Beginning Visual C#® 2005 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.