Vasile Tomoiaga
Vasile Tomoiaga

Reputation: 1747

Get the CustomAttributes of a specific member

Is there any way to get the custom attributes of a specific object I am receiving in a method?

I do not want nor can to iterate over Type.GetMembers() and search for my member. I have the object, which is also a member, that has the attribute.

How do I get the attribute?

class Custom
{
    [Availability]
    private object MyObject = "Hello";

    private void Do(object o)
    {
        //does object 'o' has any custom attributes of type 'Availability'?
    }

    //somewhere I make the call: Do(MyObject)

}

Upvotes: 1

Views: 252

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500514

No. Objects don't have attributes - members do. By the time you're in the "Do" method, there's no record of the fact that you called Do(MyObject) vs Do(MyOtherFieldWhichHasTheSameValue).

If you need to look up the attributes on a member, you'll basically have to pass in the relevant MemberInfo, not what it happens to evaluate to.

Upvotes: 2

leppie
leppie

Reputation: 117230

You cannot do this without at least 1 Reflection call. After that, save the value somehow.

Example:

abstract MyBase
{
  public string Name;
  protected MyBase()
  {
    //look up value of Name attribute and assign to Name
  } 
}

[Name("Foo")]
class MyClass : MyBase
{
}

Upvotes: 1

Related Questions