none
How can I determine the object that an attribute applies to from inside the attribute? RRS feed

  • Question

  • Hello:

    I have a custom attribute called MyAttribute.  From inside MyAttribute, I would like to gather some information about the object it applies to.  For example, I would like to know if the attribute is currently being applied to a class, and then act accordingly.  Can this be done?  If I was unclear, then please let me know.

    Thank you very much.
    MCP
    Friday, August 7, 2009 5:12 PM

Answers

  • No, this isn't possible.

    Attributes are not intended to supply much "intelligence".  They function mainly as tags and it is up to the reader to figure out what to do when it sees a class, method, etc. that is tagged with the attribute.

    • Marked as answer by webJose Saturday, August 8, 2009 1:54 AM
    Friday, August 7, 2009 10:12 PM
  • The only way to retrieve the value of an attribute is with the GetCustomAttributes() method.  Chicken-and-egg, that always requires type info for the class/method/property/field first.  There is no dictionary that maps an attribute to a collection of types that applied it.  Although you can make one by iterating the types in an assembly.  Slowly.

    Hans Passant.
    • Marked as answer by webJose Saturday, August 8, 2009 1:54 AM
    Friday, August 7, 2009 11:49 PM
    Moderator

All replies

  • No, this isn't possible.

    Attributes are not intended to supply much "intelligence".  They function mainly as tags and it is up to the reader to figure out what to do when it sees a class, method, etc. that is tagged with the attribute.

    • Marked as answer by webJose Saturday, August 8, 2009 1:54 AM
    Friday, August 7, 2009 10:12 PM
  • The only way to retrieve the value of an attribute is with the GetCustomAttributes() method.  Chicken-and-egg, that always requires type info for the class/method/property/field first.  There is no dictionary that maps an attribute to a collection of types that applied it.  Although you can make one by iterating the types in an assembly.  Slowly.

    Hans Passant.
    • Marked as answer by webJose Saturday, August 8, 2009 1:54 AM
    Friday, August 7, 2009 11:49 PM
    Moderator
  • Thank you fellows for your responses.  So I am stuck with typeof() and enums and string literals in constructor arguments and properties.  A one way thing.

    I guess then that I will have to live with it, as I have no intention in developing an inventory of attributes. :-)

    Cheers!
    MCP
    Saturday, August 8, 2009 1:53 AM