Chapter 6. Functions

WHAT YOU WILL LEARN IN THIS CHAPTER

  • How to define and use simple functions that don't accept or return any data

  • How to transfer data to and from functions

  • Working with variable scope

  • How to use command-line arguments with the Main() function

  • How to supply functions as members of struct types

  • How to use function overloading

  • How to use delegates

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. Performing an operation on your data 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 nearly 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.

Note

Functions of the specific type examined in this chapter ...

Get Beginning Visual C# 2010 now with O’Reilly online learning.

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