Prev | Current Page 176 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Default
.GetHashCode(first) * 37 +
EqualityComparer.Default
.GetHashCode(second);
}
}
Listing 3.6 is very straightforward. The constituent values are stored in appropriately
typed member variables, and access is provided by simple read-only properties. We
Listing 3.6 Generic class representing a pair of values
85 Advanced generics
implement IEquatable> to give a strongly typed API that will
avoid unnecessary execution time checks. The equality and hash-code computations
both use the default equality comparer for the two type parameters??”these handle
nulls for us automatically, which makes the code somewhat simpler.5
If we wanted to support sorting, we could implement IComparer >, perhaps ordering by the first component and then the second.
This kind of type is a good candidate for bearing in mind what functionality you might
want, but not actually implementing until you need it.
We??™ve finished looking at our ???intermediate??? features now. I realize it can all seem
complicated at first sight, but don??™t be put off: the benefits far outweigh the added
complexity. Over time they become second nature. Now that you??™ve got the Pair class
as an example, it might be worth looking over your own code base to see whether
there are some patterns that you keep reimplementing solely to use different types.


Pages:
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188