Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the attached type from within a custom attribute?

I have a custom attribute which can be assigned to a class, [FooAttribute]. What I would like to do, from within the attribute, is determine which type has actually used me. e.g. If I have:

[FooAttribute]
public class Bar
{
}

In the code for FooAttribute, how can I determine it was Bar class that added me? I'm not specifically looking for the Bar type, I just want to set a friendly name using reflection. e.g.

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

public class FooAttribute()
{
  public FooAttribute()
  {
    // How do I get the target types name? (as a default)
  }
}
like image 616
Mark Ingram Avatar asked Nov 09 '08 11:11

Mark Ingram


1 Answers

First off, you might consider the existing [DisplayName] for keeping friendly names. As has already been covered, you simply can't get this information inside the attribute. You can look up the attribute from Bar, but in general, the only way to do it from the attribute would be to pass the type into the attribute - i.e.

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

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

Note that for i18n, resx, etc; you can subclass DisplayNameAttribute and provide lookup from keys by overriding the DisplayName getter.

like image 126
Marc Gravell Avatar answered Oct 19 '22 03:10

Marc Gravell