Search code examples
c#asp.net-web-apisystem.reflection

C# Reflection - GetCustomAttributes for Type gets attribute from parent class


Let's say I have two classes, the base class has a custom attribute:

[MyAttribute]
public class BaseModel
{
    public string Id { get; set; }

    public string Name { get; set; }
}

public class InheritedModel : BaseModel
{
    public string CompanyName { get; set; }

    public int Amount { get; set; }
}

When I'm working with inherited class, like

// member.DeclaringType is InheritedModel 

if (member.DeclaringType.GetCustomAttributes(typeof(MyAttribute)).Any())
{
   // returns true
}

I expect this should be false because InheritedModel has not MyAttribute attribute directly.

It it correct behaviour? How can I divide parents and inheritors in condition above?


Solution

  • GetCustromAttributes has an overload which lets you specify if you want to search ancestor classes as well.

    It seems to default to true (though it doesn't say in the docs) so try passing false

    member.DeclaringType.GetCustomAttributes(typeof(MyAttribute), false).Any()