Prev | Current Page 215 | Next

Jon Skeet

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

We want a derivation type
constraint but in the other direction, constraining the S to be somewhere up the
inheritance tree of T instead of down.
Given that this isn??™t possible, what can we do? There are fewer options this time
than before. First, you could create a generic class with the following declaration:
ComparisonHelper : IComparer
where TDerived : TBase
You??™d then create a constructor that takes (and stores) an IComparer as a
parameter. The implementation of IComparer would just return the result
of calling the Compare method of the IComparer. You could then sort the
List by creating a new ComparisonHelper that uses the
area comparison.
The second option is to make the area comparison class generic, with a derivation
constraint, so it can compare any two values of the same type, as long as that type
implements IShape. Of course, you can only do this when you??™re able to change the
comparison class??”but it??™s a nice solution when it??™s available.
13 You didn??™t really expect to get through the whole book without seeing a shape-related example, did you?
106 CHAPTER 3 Parameterized typing with generics
Notice that the various options for both covariance and contravariance use more
generics and constraints to express the interface in a more general manner, or to provide
generic ???helper??? methods.


Pages:
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227