13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

84 CHAPTER 3 Parameterized typ<strong>in</strong>g with generics<strong>in</strong>stances of our type to play nicely when used as keys <strong>in</strong> a dictionary. List<strong>in</strong>g 3.6 givesthe complete code.List<strong>in</strong>g 3.6Generic class represent<strong>in</strong>g a pair of valuesus<strong>in</strong>g System;us<strong>in</strong>g System.Collections.Generic;public sealed class Pair: IEquatable{private readonly TFirst first;private readonly TSecond second;}public Pair(TFirst first, TSecond second){this.first = first;this.second = second;}public TFirst First{get { return first; }}public TSecond Second{get { return second; }}public bool Equals(Pair other){if (other == null){return false;}return EqualityComparer.Default.Equals(this.First, other.First) &&EqualityComparer.Default.Equals(this.Second, other.Second);}public override bool Equals(object o){return Equals(o as Pair);}public override <strong>in</strong>t GetHashCode(){return EqualityComparer.Default.GetHashCode(first) * 37 +EqualityComparer.Default.GetHashCode(second);}List<strong>in</strong>g 3.6 is very straightforward. The constituent values are stored <strong>in</strong> appropriatelytyped member variables, and access is provided by simple read-only properties. WeLicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!