How can I determine the attached type from a custom attribute?

I have a custom attribute that can be assigned to a class [FooAttribute]

. What I would like to do, from within the attribute, determines which type was actually using me. e.g. If I have:

[FooAttribute]
public class Bar
{
}

      

In the FooAttribute code, how can I tell if there was a Bar class that added me? I'm not looking for the Bar type, I just want to set a friendly name using reflection. eg.

[FooAttribute(Name="MyFriendlyNameForThisClass")]
public class Bar
{
}

public class FooAttribute()
{
  public FooAttribute()
  {
    // How do I get the target types name? (as a default)
  }
}

      

+5


source to share


4 answers


First, you can consider an existing [DisplayName]

friendly name storage. As already described, you simply cannot get this information inside an attribute. You can find the attribute from Bar, but in general the only way to do it from the attribute is to pass the type to the attribute - ie

[Foo("Some name", typeof(Bar)]

      



What exactly do you want to do? There may be other options ...

Please note that for i18n, resx, etc .; you can subclass DisplayNameAttribute

and provide key search by overriding the getter DisplayName

.

+5


source


To clarify. An attribute, whether built-in or custom, represents only metadata for a class or class member, and the attribute itself does not have any indication that it is associated with anything.



  • The type knows its own metadata
  • Metadata (in this case, an attribute) doesn't know who it belongs to
+3


source


From your suggestion "I just want to set a friendly name using reflection". I think you want to set the name "MyFriendlyNameForThisClass" for the attribute at runtime. if so, I don't think it is possible. See this thread .

+1


source


It's awkward, but you can iterate over all the classes in an assembly, testing each one for a custom attribute that the instance "is".

+1


source







All Articles