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.

Generics and Extension Methods ❘ 353<br />

Example program Switcher uses the following code to define a generic Switch method.<br />

public static class Switcher<br />

{<br />

// Switch two values.<br />

public static void Switch(ref T value1, ref T value2)<br />

{<br />

T temp = value1;<br />

value1 = value2;<br />

value2 = temp;<br />

}<br />

}<br />

The Switch method takes a generic type T. It also takes two parameters of type T. It creates a<br />

temporary variable of type T and uses it to swap the two values.<br />

The following code shows how the main program uses the Switch method.<br />

string value1 = value1TextBox.Text;<br />

string value2 = value2TextBox.Text;<br />

Switcher.Switch(ref value1, ref value2);<br />

value1TextBox.Text = value1;<br />

value2TextBox.Text = value2;<br />

This code gets two string values from TextBoxes. It uses the Switch method to swap their values<br />

and displays the results.<br />

Type Not Required<br />

In this example, Visual Studio is smart enough to infer the type parameter because<br />

the program is passing two string values into the method. In cases such as this, the<br />

code can omit the type parameter as in the following code.<br />

Switcher.Switch(ref value1, ref value2);<br />

You may want to include the type parameter anyway to make the code more<br />

self-documenting.<br />

Note that the Switcher class is not generic but it contains a generic method. You can also create<br />

generic classes that contain both generic and nongeneric methods.<br />

Generics and Extension Methods<br />

Extension methods let you add new features to existing classes, whether they’re generic or nongeneric.<br />

For example, suppose you have an application that uses a List. This class is a generic collection<br />

class defined in the System.Collections.Generic namespace. It’s not defined in your code<br />

so you can’t modify it. However, you can add extension methods to it.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!