0

I am repeating myself, and violating DRY. What I need is a base class that implements the operator == and != and GetHashCode and Equals. The base class must list all properties (through reflection?) of the top most derived class. And compare these properties in these operator functions, or combine their hashcodes in GetHashCode.

Example pseudo code:

    public static Boolean operator == (KeyValue A, KeyValue B)
    {
        List<PropertiesOfKeyValueClass> Properties = Reflection.GetProperties(KeyValue);
        foreach (Property prop in Properties)
        {
            if (A.prop != B.Prop) return false;
        }
    }

I can't imagine this isn't implemented in the .Net framework already, but I can't find it. So instead of 'inventing the wheel' I thought I could ask on StackOverflow first.

Mike de Klerk
  • 11,906
  • 8
  • 54
  • 76
  • 1
    Not only it is not implemented, it's also a very good thing that it isn't. Default equality / hash code should not be too smart, but most importantly, they must not be slow. An approach based on properties and reflection is definitely too smart, and for an operation so basic it wold be prohibitively slow. – Sergey Kalinichenko Aug 12 '13 at 10:44
  • Yes you are right indeed. In my application its not all too important whether it takes (arbitrary value of) 50ms longer to compare an object. But it is bad coding practice indeed. But couldn't I build a static cache of properties. So it only takes time to reflect the properties for the very first access of the class? – Mike de Klerk Aug 12 '13 at 12:07
  • Sure, you can do that. Moreover, it is entirely possible to build a LINQ expression based on the properties reflected from a `Type`, such that you would pass it an object, and it would compute its hash code (or pass it a pair of objects, and get the result of comparing them for equality). You would be able to cache these expressions for future use, speeding the process up to acceptable levels. – Sergey Kalinichenko Aug 12 '13 at 12:52

0 Answers0