Graviton
Graviton

Reputation: 83296

Test whether a property is declared in the derived class

I have two classes

public class A
{
  public int BaseA
{get;set;}
}

public Class B: A
{
 public int BaseB
{get;set;}
}

I can get the Properties for the Class B by using typeof(B).GetProperties(). However, this would include both the BaseA and BaseB properties. But I want to obtain the BaseB property only.

Note: I found the solution, it's

  B boy = new B();
            var pList = boy.GetType().GetProperties(BindingFlags.Public |
                  BindingFlags.DeclaredOnly |
                  BindingFlags.Instance);
            Assert.AreEqual(1, pList.Length);

A similar solution can be found here.

Upvotes: 0

Views: 123

Answers (1)

Ants
Ants

Reputation: 2668

Look at using BindingFlags.DeclaredOnly when calling Type.GetProperties().

Upvotes: 3

Related Questions