[Serializable]
public struct EmployeeId : IEquatable<EmployeeId>
{
private readonly char prefix;
private readonly int number;
public EmployeeId(string id)
{
if (id == null) throw new ArgumentNullException("id");
prefix = (id.ToUpper())[0];
int numLength = id.Length - 1;
number = int.Parse(id.Substring(1, numLength > 6 ? 6 : numLength));
}
public override string ToString()
{
return prefix.ToString() + string.Format("{0,6:000000}", number);
}
public override int GetHashCode()
{
return (number ^ number << 16) * 0x15051505;
}
public bool Equals(EmployeeId other)
{
return (prefix == other.prefix && number == other.number);
}
public override bool Equals(object obj)
{
if (!(obj is EmployeeId)) return false;
return Equals((EmployeeId)obj);
}
public static bool operator ==(EmployeeId emp1, EmployeeId emp2)
{
return emp1.Equals(emp2);
}
public static bool operator !=(EmployeeId emp1, EmployeeId emp2)
{
return !emp1.Equals(emp2);
}
}
[Serializable]
public class Employee
{
private string name;
private decimal salary;
private readonly EmployeeId id;
public Employee(EmployeeId id, string name, decimal salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
public override string ToString()
{
return String.Format("{0}: {1, -20} {2:C}", id.ToString(), name, salary);
}
}
class Program
{
static void Main()
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Dictionary<EmployeeId, Employee> employees =
new Dictionary<EmployeeId, Employee>(31);
EmployeeId idJeff = new EmployeeId("C7102");
Employee jeff = new Employee(idJeff, "Jeff Gordon",
5164580.00m);
employees.Add(idJeff, jeff);
Console.WriteLine(jeff);
EmployeeId idTony = new EmployeeId("C7105");
Employee tony = new Employee(idTony, "Tony Stewart", 4814200.00m);
employees.Add(idTony, tony);
Console.WriteLine(tony);
EmployeeId idDenny = new EmployeeId("C8011");
Employee denny = new Employee(idDenny, "Denny Hamlin", 3718710.00m);
employees.Add(idDenny, denny);
Console.WriteLine(denny);
EmployeeId idCarl = new EmployeeId("F7908");
Employee carl = new Employee(idCarl, "Carl Edwards", 3285710.00m);
employees[idCarl] = carl;
Console.WriteLine(carl);
EmployeeId idMatt = new EmployeeId("F7203");
Employee matt = new Employee(idMatt, "Matt Kenseth", 4520330.00m);
employees[idMatt] = matt;
Console.WriteLine(matt);
while (true)
{
try
{
Console.Write("Enter employee id (X to exit)> ");
string userInput = Console.ReadLine();
userInput = userInput.ToUpper();
if (userInput == "X") break;
EmployeeId id = new EmployeeId(userInput);
Employee employee;
if (!employees.TryGetValue(id, out employee))
{
Console.WriteLine("Employee with id {0} does not exist",
id);
}
else
{
Console.WriteLine(employee);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
}