How do I compare two PropertyInfos or methods reliably?

Posted by Rob Ashton on Stack Overflow See other posts from Stack Overflow or by Rob Ashton
Published on 2011-01-09T17:50:11Z Indexed on 2011/01/09 17:53 UTC
Read the original article Hit count: 190

Filed under:
|

Same for methods too:

I am given two instances of PropertyInfo or methods which have been extracted from the class they sit on via GetProperty or GetMember etc, (or from a MemberExpression maybe).

I want to determine if they are in fact referring to the same Property or the same Method so

(propertyOne == propertyTwo)

or (methodOne == methodTwo)

Clearly that isn't going to actually work, you might be looking at the same property, but it might have been extracted from different levels of the class hierarchy (in which case generally, propertyOne != propertyTwo)

Of course, I could look at DeclaringType, and re-request the property, but this starts getting a bit confusing when you start thinking about

  • Properties/Methods declared on interfaces and implemented on classes
  • Properties/Methods declared on a base class (virtually) and overridden on derived classes
  • Properties/Methods declared on a base class, overridden with 'new' (in IL world this is nothing special iirc)

At the end of the day, I just want to be able to do an intelligent equality check between two properties or two methods, I'm 80% sure that the above bullet points don't cover all of the edge cases, and while I could just sit down, write a bunch of tests and start playing about, I'm well aware that my low level knowledge of how these concepts are actually implemented is not excellent, and I'm hoping this is an already answered topic and I just suck at searching.

The best answer would give me a couple of methods that achieve the above, explaining what edge cases have been taken care of and why :-)

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection