What is the best way to make a generic equivalence function for two Dictionaries, whose keys and values are value types?
Right now I have a Dictionary<string, bool>, and have created an extension method that (I think) works to test for equivalence between two Dictionary<string, bool>.
I wanted to make it more generic. And my first thought was to make it like this:
public static bool EquivalentTo<K, V>(this IDictionary<K, V> lhs, IDictionary<K, V> rhs) where K: struct where V: struct { }
However, this doesn’t work because strings are immutable reference types, and NOT a value type.
So how would one go about generic-izing my original Equivalence test for Dictionary<string, bool> ?
Why do you want to restrict
KandVto being value types in the first place? I suggest you just remove the constraints. There are ‘interesting’ things about dictionaries though – are two dictionaries which happen to have the same entries, but use different equality comparers equivalent?IDictionary<,>doesn’t have an equality comparer property, unfortunately, so you may need to provide on to your equivalence method. You’ll need to consider what it even means to be equivalent here.For example, two dictionaries both with case-insensitive equality comparers might have { ‘FOO’, true } and { ‘foo’, true } – to some extent they’re equivalent, but to some extent they aren’t. It depends on what you want to use the equivalence relation for.
EDIT: Here’s an example which should be fine in most cases, but could give odd results if the two dictionaries treat keys differently:
Untested, but let me know if it does what you want…