15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

252 ❘ ChaPTer 10 cOllectiOns<br />

private readonly EmployeeId id;<br />

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

{<br />

this.id = id;<br />

this.name = name;<br />

this.salary = salary;<br />

}<br />

}<br />

public override string ToString()<br />

{<br />

return String.Format("{0}: {1, -20} {2:C}",<br />

id.ToString(), name, salary);<br />

}<br />

code snippet DictionarySample/Employee.cs<br />

In the Main() method of the sample application, a new Dictionary instance is created,<br />

where the key is of type EmployeeId <strong>and</strong> the value is of type Employee. The constructor allocates a capacity<br />

of 31 elements. Remember, the capacity is based on prime numbers. However, when you assign a value<br />

that is not a prime number, you don’t need to worry. The Dictionary class itself takes the<br />

next prime number that follows the integer passed to the constructor to allocate the capacity. The employee<br />

objects <strong>and</strong> IDs are created <strong>and</strong> added to the dictionary with the Add() method. Instead of using the Add()<br />

method, you can also use the indexer to add keys <strong>and</strong> values to the dictionary, as shown with the employees<br />

Dale <strong>and</strong> Jeff:<br />

static void Main()<br />

{<br />

var employees = new Dictionary(31);<br />

var idKyle = new EmployeeId("T3755");<br />

var kyle = new Employee(idKyle, "Kyle Bush", 5443890.00m);<br />

employees.Add(idKyle, kyle);<br />

Console.WriteLine(kyle);<br />

var idCarl = new EmployeeId("F3547");<br />

var carl = new Employee(idCarl, "Carl Edwards", 5597120.00m);<br />

employees.Add(idCarl, carl);<br />

Console.WriteLine(carl);<br />

var idJimmie = new EmployeeId("C3386");<br />

var jimmie = new Employee(idJimmie, "Jimmie Johnson", 5024710.00m);<br />

employees.Add(idJimmie, jimmie);<br />

Console.WriteLine(jimmie);<br />

var idDale = new EmployeeId("C3323");<br />

var dale = new Employee(idDale, "Dale Earnhardt Jr.", 3522740.00m);<br />

employees[idDale] = dale;<br />

Console.WriteLine(dale);<br />

var idJeff = new EmployeeId("C3234");<br />

var jeff = new Employee(idJeff, "Jeff Burton", 3879540.00m);<br />

employees[idJeff] = jeff;<br />

Console.WriteLine(jeff);<br />

code snippet DictionarySample/Program.cs<br />

After the entries are added to the dictionary, inside a while loop employees are read from the dictionary.<br />

The user is asked to enter an employee number to store in the variable userInput. The user can exit the<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!