03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

136 ❘ CHAPTER 6 Methods<br />

TIP If you name static extension classes as in StringExtensions, it’s easy to<br />

tell which class you are extending and that this is an extension class.<br />

The static RemoveNonLetters method’s first parameter uses the this keyword, so you know this<br />

is an extension method. The parameter following this has type string so this extension method<br />

extends the string class.<br />

The method’s code loops through a string’s characters and replaces any that are not letters with<br />

question marks. It then returns the result.<br />

The following code shows how a program might use this method.<br />

string text = "When in worry or in doubt, run in circles scream and shout";<br />

Console.WriteLine(text.RemoveNonLetters());<br />

This code creates a string variable. It then invokes the RemoveNonLetters method just as if that<br />

were a normal method defined by the string class.<br />

Lambda Expressions<br />

Lambda expressions are methods defined within the flow of the program’s code instead of as<br />

separate methods. Often they are defined, used, and forgotten in a single statement without ever<br />

being given a name.<br />

You can use normal methods instead of lambda expressions, but sometimes lambda expressions<br />

make the code simpler and easier to read. Many LINQ queries (described in Chapter 8, “LINQ”)<br />

use functions to select values that meet certain criteria. You can write those functions as separate<br />

methods but they may only be used once inside the LINQ query so making them separate methods<br />

clutters the code unnecessarily.<br />

The following sections group lambda expressions into three categories: expression lambdas, statement<br />

lambdas, and async lambdas.<br />

Expression Lambdas<br />

An expression lambda consists of a list of zero or more parameters, the => operator, and a single<br />

expression that evaluates to some result. The lambda expression returns the result of the expression.<br />

The following code uses a simple expression lambda (in bold).<br />

Action note = () => MessageBox.Show("Hi");<br />

note();<br />

Recall from the section “Delegates” in Chapter 4 that Action is a type that represents a method that<br />

takes no parameters and returns void. The code creates a variable note with that type. It sets that<br />

variable equal to the expression lambda defined by () => MessageBox.Show("Hi"). This lambda<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!