Question

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)

}
Was it helpful?

Solution

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.

OTHER TIPS

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
{
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top