I am creating a generic class to hold widgets and I am having trouble implementing the contains method:
public class WidgetBox<A,B,C>
{
public bool ContainsB(B b)
{
// Iterating thru a collection of B's
if( b == iteratorB ) // Compiler error.
...
}
}
Error: Operator ‘==’ cannot be applied to operands of type ‘V’ and ‘V’
If I can not compare types, how am I to implement contains? How do dictionaries, lists, and all of the other generic containers do it??
You have a few options here
The first is to use
Object.Equals:Be careful using this option; if
Bdoes not overrideObject.Equalsthen the default comparsion is reference equality whenBis a reference type and value equality whenBis a value type. This might not be the behavior that you are seeking and is why without additional information I would consider one of the next two options.The second is to add a constraint that
BisIComparable:so that
A third is to require an
IEqualityComparer<B>be passed to the constructor ofWidgetBoxThen:
With this last option you can provide an overload that defaults to
EqualityComparer<T>.Default: