views:

67

answers:

2

Hello,

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)

}
+1  A: 

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
{
}
leppie
+1  A: 

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.

Jon Skeet
I thought about that, but also hoped that there is a clever way to get the attributes, still. Thanks.
Vasi