15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

124 ❘ ChaPTer 5 Generics<br />

The method Swap() defines T as a generic type that is used for two arguments <strong>and</strong> a variable temp:<br />

void Swap(ref T x, ref T y)<br />

{<br />

T temp;<br />

temp = x;<br />

x = y;<br />

y = temp;<br />

}<br />

A generic method can be invoked by assigning the generic type with the method call:<br />

int i = 4;<br />

int j = 5;<br />

Swap(ref i, ref j);<br />

However, because the <strong>C#</strong> compiler can get the type of the parameters by calling the Swap() method, it is<br />

not required to assign the generic type with the method call. The generic method can be invoked as simply<br />

as non-generic methods:<br />

int i = 4;<br />

int j = 5;<br />

Swap(ref i, ref j);<br />

generic methods example<br />

Here’s an example where a generic method is used to accumulate all elements of a collection. To show<br />

the features of generic methods, the following Account class that contains Name <strong>and</strong> Balance properties<br />

is used:<br />

public class Account<br />

{<br />

public string Name { get; private set; }<br />

public decimal Balance { get; private set; }<br />

}<br />

public Account(string name, Decimal balance)<br />

{<br />

this.Name = name;<br />

this.Balance = balance;<br />

}<br />

code snippet GenericMethods/Account.cs<br />

All the accounts where the balance should be accumulated are added to an accounts list of type<br />

List:<br />

var accounts = new List()<br />

{<br />

new Account("Christian", 1500),<br />

new Account("Stephanie", 2200),<br />

new Account("Angela", 1800)<br />

};<br />

code snippet GenericMethods/Program.cs<br />

A traditional way to accumulate all Account objects is by looping through all Account objects with<br />

a foreach statement, as shown here. Because the foreach statement uses the IEnumerable interface<br />

to iterate the elements of a collection, the argument of the AccumulateSimple() method is of type<br />

IEnumerable. The foreach statement works with every object implementing IEnumerable. This way,<br />

the AccumulateSimple() method can be used with all collection classes that implement the interface<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!