It implements a useful generic type??”a Pair
, which just holds two values together, like a key/value pair, but with
no expectations as to the relationship between the two values. As well as providing properties
to access the values themselves, we??™ll override Equals and GetHashCode to allow
Listing 3.5 Comparisons using == and != using reference comparisons
Compares
references
B
Compares using
string overload
C
Caution!
Possibly
unexpected
behavior!
84 CHAPTER 3 Parameterized typing with generics
instances of our type to play nicely when used as keys in a dictionary. Listing 3.6 gives
the complete code.
using System;
using 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 int GetHashCode()
{
return EqualityComparer.
Pages:
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187