O'Reilly logo

Beginning Microsoft® Visual C#® 2008 by Eric White, Morgan Skinner, Jon D. Reid, Jacob Hammer Pedersen, Christian Nagel, Karli Watson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Functions

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 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. Often, some tasks — such as finding the highest value in an array, for example—may need to be performed at several points in a program. You can 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, but this term has a very specific meaning in .NET programming that will only become clear later in this book. So for now this term is not to 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 in your code, and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required