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.

192 ❘ ChaPTer 8 deleGAtes, lAmbdAs, And events<br />

}<br />

}<br />

sortArray[i + 1] = temp;<br />

swapped = true;<br />

}<br />

}<br />

} while (swapped);<br />

code snippet BubbleSorter/BubbleSorter.cs<br />

To use this class, you need to define some other class, which you can use to set up an array that needs<br />

sorting. For this example, assume that the Mortimer Phones mobile phone company has a list of employees<br />

<strong>and</strong> wants them sorted according to salary. The employees are each represented by an instance of a class,<br />

Employee, which looks similar to this:<br />

class Employee<br />

{<br />

public Employee(string name, decimal salary)<br />

{<br />

this.Name = name;<br />

this.Salary = salary;<br />

}<br />

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

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

public override string ToString()<br />

{<br />

return string.Format("{0}, {1:C}", Name, Salary);<br />

}<br />

}<br />

public static bool CompareSalary(Employee e1, Employee e2)<br />

{<br />

return e1.Salary < e2.Salary;<br />

}<br />

code snippet BubbleSorter/Employee.cs<br />

Notice that to match the signature of the Func delegate, you have to define CompareSalary<br />

in this class as taking two Employee references <strong>and</strong> returning a Boolean. In the implementation the<br />

comparison based on salary is performed.<br />

Now you are ready to write some client code to request a sort:<br />

using System;<br />

namespace Wrox.ProCSharp.Delegates<br />

{<br />

class Program<br />

{<br />

static void Main()<br />

{<br />

Employee[] employees =<br />

{<br />

new Employee("Bugs Bunny", 20000),<br />

new Employee("Elmer Fudd", 10000),<br />

new Employee("Daffy Duck", 25000),<br />

new Employee("Wile Coyote", 1000000.38m),<br />

new Employee("Foghorn Leghorn", 23000),<br />

new Employee("RoadRunner", 50000)<br />

};<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!