Reflecting derived classes in C#

Posted by rook on Stack Overflow See other posts from Stack Overflow or by rook
Published on 2010-05-01T10:59:31Z Indexed on 2010/05/01 11:07 UTC
Read the original article Hit count: 440

Filed under:
|
|

Let's assume there's a class with a virtual property (let's call it 'P'). It's overridden in a deriving class. Now I want to use something like this: obj.GetType().GetProperty("P") to get info about the overriding property. This search is ambigous, because there are two "P" properties (base and override). So I typed: obj.GetType().GetProperty("P", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)

It returns the overriding "P" only, but what if I can't guess in compile time if there's an override at all? The latter call would return null. The case is even more complicated, if the hierarchy of inheritance is bigger.

In other words, I want to get the 'top-most' override available, otherwise - the base property. What is the cleanest way to achieve the aim? Only one I know at the moment is to go through all properties and check name and declaring type.

© Stack Overflow or respective owner

Related posts about reflection

Related posts about c#