MrFox
MrFox

Reputation: 5106

check if propertyInfo implements a class

How to find if a PropertyInfo implments a specific class (and therefore must also be a class). I know how to check if the PropertyInfo is of a specific type, but that does not work for checking whether it derives a type:

public class Foo
{
    public Foo foo { get; set; }
    public Bar bar { get; set; }

    public void CheckStuff()
    {
        foreach (var property in this.GetType().GetProperties())
            Debug.WriteLine(Bar.IsOfType(property));
    }
}

public class Bar : Foo
{
    public static bool IsOfType(PropertyInfo member)
    {
        return member.PropertyType == typeof(Foo);
    }
}

Result:

True
False

How to change the code so the second result is also true?

Upvotes: 2

Views: 598

Answers (1)

Lee
Lee

Reputation: 144126

public static bool IsOfType(PropertyInfo member)
{
    return typeof(Foo).IsAssignableFrom(member.PropertyType);
}

Upvotes: 7

Related Questions