If one is designing an interface like ILookup
(for simplicity, assume it's simply ICheckIfContained
, so the type of the item's value wouldn't matter), what would be the ideal type of variance with respect to the first parameter?
Checking to see if an ICheckIfContained<Animal>
contains a particular Cat
would be a natural operation, and would be type-safe under normal rules of contravariance.
Checking to see if an ICheckIfContained<Cat>
contains a particular Animal
would not be type-safe under normal rules of contravariance, but would be natural and well-defined (if the Animal
in question is not a Cat
, the proper behavior would be for the ICheckIfContained
to say it does not contain the animal in question).
Checking to see if an ICheckIfContained<Cat>
contains a particular Dog
would not be particularly useful (the answer would always be "no") but the answer would be well-defined. Note that the answer in this scenario, unlike the previous one, could be determined statically.
One approach would be to have an ICheckIfContained
be a non-generic interface, and simply accept a parameter of type Object
. This would seem rather inefficient, however, in cases where the list contained nothing but a single type of struct. On the other hand, if it's a generic interface, then the compiler would be unable to allow its use in the covariant scenario (passing in a parameter whose declared type is a parent of the expected type, such that the passed-in object might or might not be of the expected type).
Is there any nice pattern for getting the efficiency of generics in cases where the compiler can confirm that everything is the same type, while still allowing the general-case behavior of checking for whether an object of parent type is in the collection of child type?
backtick
worked in comments, but it didn't dawn on me to think it might also work in questions/answers, given that questions use HTML (like <B>) for things like bold that, in answers, are handled with punctuation marks (asterisks, in the case of bold). I thought in questions/answers one was supposed to use something like <TT>, although the TT tag in particular doesn't work here. – supercat