O'Reilly logo

C# 5.0 Programmer's Reference by Rod Stephens

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 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 ...

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