Chapter 6 Methods

What’s in This Chapter

  • Method declarations
  • Optional and named parameters
  • Method overloading
  • Extension methods
  • Lambda expressions
  • Covariance and contravariance
  • Asynchronous method execution

Wrox.com Downloads for This Chapter

Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wrox.com/go/csharp5programmersref on the Download Code tab.

Methods enable you to break an otherwise unwieldy chunk of code into manageable pieces. They enable you to extract code that you may need to use under more than one circumstance and place it in a single location where you can call it as needed.

This enables you to maintain and update the code in a single location. If you later need to modify the code, you need to do it only in one place, so you don’t need to keep multiple copies of the code synchronized.

This chapter describes methods and explains the syntax for declaring them. It also provides some tips for making methods more maintainable.

Method Declarations

In C# all methods must be inside a class. The syntax for creating a method follows:

«attributes» «accessibility» «modifiers» return_type nameparameters»)
{
    code...
}

Many of these pieces of the declaration are similar ...

Get C# 5.0 Programmer's Reference 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.