Search code examples
c#reflectionpdb-files

How do I get the parameters passed in to the constructor of an attribute?


I'm working on a documentation generator. MSDN documentation shows the parameters passed to Attributes when they are applied. Such as [ComVisibleAttribute(true)]. How would I get those parameter values and/or the constructor called in my c# code via reflection, pdb file or otherwise?

To clarify> If someone has documented a method that has an attribute on it like so:

/// <summary> foo does bar </summary>
[SomeCustomAttribute("a supplied value")]
void Foo() {
  DoBar();
}

I want to be able to show the signature of the method in my documentation like so:

Signature:

[SomeCustomAttribute("a supplied value")]
void Foo();

Solution

  • If you have a member for which you want to get the custom attributes and the constructor arguments, you can use the following reflection code:

    MemberInfo member;      // <-- Get a member
    
    var customAttributes = member.GetCustomAttributesData();
    foreach (var data in customAttributes)
    {
        // The type of the attribute,
        // e.g. "SomeCustomAttribute"
        Console.WriteLine(data.AttributeType);
    
        foreach (var arg in data.ConstructorArguments)
        {
            // The type and value of the constructor arguments,
            // e.g. "System.String a supplied value"
            Console.WriteLine(arg.ArgumentType + " " + arg.Value);
        }
    }
    

    To get a member, start with getting the type. There are two ways to get a type.

    1. If you have an instance obj, call Type type = obj.GetType();.
    2. If you have a type name MyType, do Type type = typeof(MyType);.

    Then you can find, for example, a particular method. Look at the reflection documentation for more info.

    MemberInfo member = typeof(MyType).GetMethod("Foo");