Erik Porter's Blog

Life and Development at Microsoft and Other Technology Discussions

News

    Getting Attributes using Reflection

    Just a quick note to all of you out there who are not Reflection Gurus (I'm sure not yet).  I was working the VBCommenter and I noticed that the COM Name as hard coded in quite a few places for the Add-In.  That wasn't going to work for me, so since the Name for the Command in the IDE (VS.NET) is the COM ProgId given to the Class + "." + the Name (in this case "VBCommenter"), I thought it would be cool to build it dynamically, by grabbing the ProgId.

    So I'm looking around at the Type Class to see how I can get at the ProgId so I can build the string for the Command Name.  I saw the Attributes Property (TypeAtrributes) and couldn't find it there, so following the naming conventions, I started looking for a GetAttributes Method, but there wasn't one...thought this was strange and started searching the help for information on Attributes.  Not much help for what I was looking for.  After a while though, I happened to stumbled across GetCustomAttributes, which is exactly what I need and it worked great!

    Now my problem is why is it called GetCustomAttributes.  It doesn't seem to follow the same naming conventions (i.e. GetMethods, GetProperties, etc).  Luckily a few MVP's came to my rescue in schooling me as to why it's called GetCustomAttributes and not GetAttributes.  Also, Eric Gunnerson of Microsoft gave me and in depth explanation:

    “When we originally designed the CLR, there were no [] attributes.

    In the metadata, the compiler can set attributes on the various items, so
    when we added the [] attributes, we needed a name that differentiated
    between the two.

    So,
    Attributes = bits on objects in the metadata. Things like accessibility,
    virtuality, etc.
    Custom Attributes = customizable annotations next to objects in the metadata

    There are also a few pseudo-custom attributes, where the user model is []
    attributes, but the compiler actually sets bits in the metadata instead of
    using the usual [] attribute mechanism. If you've come across an attribute
    in the code that you can't get to through GetCustomAttributes(), you've run
    into one.

    We now return you to your regular programming, already in progress.”

    So, just wanted to post about that and for anybody else looking to get the attributes that you've set for a class, method, etc, you can do so using GetCustomAttributes.

    Comments

    No Comments