I would like to use a class as key in a Dictionary which does not override Equals nor GetHashCode. It’s a class from an external library which I don’t want to modify.
So I am wondering if I can use custom “GetHashCode”/”Equals” implemantiotns just for one Dictionary? I was wondering if something like with C++ std::maps was possible
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<T>, // map::key_compare
class Alloc = allocator<T> > // map::allocator_type
> class map;
where Compare can be used to define custom comparison.
I don’t want to derive from the class because the objects are created outside using the existing class.
I could create a class which contains the original class, but that changes the access to the Dictionary.
Thanks for your ideas!
Sure – you can implement
IEqualityComparer<T>and pass that into theDictionary<,>constructor. That’s precisely the purpose of that constructor 🙂For example: