1

Possible Duplicate:
How does reflection tell me when a property is hiding an inherited member with the 'new' keyword?

Using reflection how can I tell if a property is shadowing another property? I am working on some code generation and I need that information to call said properties correctly.

Exmaple:

class A{
    int Foo {get;set;}
}

class B:A{
    string new Foo {get;set;}
}

Code I would need to generate:

someB.Foo = "";
((A)someB).Foo = 0;
Community
  • 1
  • 1
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447

1 Answers1

2

There weren't any answers marked as correct in the duplicate so I copied the one that seems to work after minor corrections.

    public static bool IsHidingMember(PropertyInfo self)
    {
        Type baseType = self.DeclaringType.BaseType;
        if (baseType == null)
            return false;

        PropertyInfo baseProperty = baseType.GetProperty(self.Name);

        if (baseProperty == null)
        {
            return false;
        }

        if (baseProperty.DeclaringType == self.DeclaringType)
        {
            return false;
        }

        var baseMethodDefinition = baseProperty.GetGetMethod().GetBaseDefinition();
        var thisMethodDefinition = self.GetGetMethod().GetBaseDefinition();

        return baseMethodDefinition.DeclaringType != thisMethodDefinition.DeclaringType;
    }
Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447