Edit

Share via


Access custom attributes

After attributes have been associated with program elements, reflection can be used to query their existence and values. .NET provides the MetadataLoadContext, which you can use to examine code that can't be loaded for execution.

MetadataLoadContext

Code loaded into the MetadataLoadContext context cannot be executed. This means that instances of custom attributes cannot be created, because that would require executing their constructors. To load and examine custom attributes in the MetadataLoadContext context, use the CustomAttributeData class. You can obtain instances of this class by using the appropriate overload of the static CustomAttributeData.GetCustomAttributes method. For more information, see How to: Inspect assembly contents using MetadataLoadContext.

The execution context

The main reflection methods to query attributes in the execution context are MemberInfo.GetCustomAttributes and Attribute.GetCustomAttributes.

The accessibility of a custom attribute is checked with respect to the assembly in which it's attached. This is equivalent to checking whether a method on a type in the assembly in which the custom attribute is attached can call the constructor of the custom attribute.

Methods such as Assembly.GetCustomAttributes(Boolean) check the visibility and accessibility of the type argument. Only code in the assembly that contains the user-defined type can retrieve a custom attribute of that type using GetCustomAttributes.

The following C# example is a typical custom attribute design pattern. It illustrates the runtime custom attribute reflection model.

System.DLL
public class DescriptionAttribute : Attribute
{
}

System.Web.DLL
internal class MyDescriptionAttribute : DescriptionAttribute
{
}

public class LocalizationExtenderProvider
{
    [MyDescriptionAttribute(...)]
    public CultureInfo GetLanguage(...)
    {
    }
}

If the runtime is attempting to retrieve the custom attributes for the public custom attribute type DescriptionAttribute attached to the GetLanguage method, it performs the following actions:

  1. The runtime checks that the type argument DescriptionAttribute to Type.GetCustomAttributes(Type type) is public, and therefore is visible and accessible.
  2. The runtime checks that the user-defined type MyDescriptionAttribute that's derived from DescriptionAttribute is visible and accessible within the System.Web.dll assembly, where it's attached to the method GetLanguage().
  3. The runtime checks that the constructor of MyDescriptionAttribute is visible and accessible within the System.Web.dll assembly.
  4. The runtime calls the constructor of MyDescriptionAttribute with the custom attribute parameters and returns the new object to the caller.

The custom attribute reflection model could leak instances of user-defined types outside the assembly in which the type is defined. This is no different from the members in the runtime system library that return instances of user-defined types, such as Type.GetMethods returning an array of RuntimeMethodInfo objects. To prevent a client from discovering information about a user-defined custom attribute type, define the type's members to be nonpublic.

The following example demonstrates the basic way of using reflection to get access to custom attributes.

using namespace System;

public ref class ExampleAttribute : Attribute
{
private:
    String^ stringVal;

public:
    ExampleAttribute()
    {
        stringVal = "This is the default string.";
    }


    property String^ StringValue
    {
        String^ get() { return stringVal; }
        void set(String^ value) { stringVal = value; }
    }
};

[Example(StringValue="This is a string.")]
public ref class Class1
{
public:
    static void Main()
    {
        System::Reflection::MemberInfo^ info = Type::GetType("Class1");
        for each (Object^ attrib in info->GetCustomAttributes(true))
        {
            Console::WriteLine(attrib);
        }
    }
};

int main()
{
    Class1::Main();
}
using System;

public class ExampleAttribute : Attribute
{
    private string stringVal;

    public ExampleAttribute()
    {
        stringVal = "This is the default string.";
    }

    public string StringValue
    {
        get { return stringVal; }
        set { stringVal = value; }
    }
}

[Example(StringValue="This is a string.")]
class Class1
{
    public static void Main()
    {
        System.Reflection.MemberInfo info = typeof(Class1);
        foreach (object attrib in info.GetCustomAttributes(true))
        {
            Console.WriteLine(attrib);
        }
    }
}
Public Class ExampleAttribute
    Inherits Attribute

    Private stringVal As String

    Public Sub New()
        stringVal = "This is the default string."
    End Sub

    Public Property StringValue() As String
        Get
            Return stringVal
        End Get
        Set(Value As String)
            stringVal = Value
        End Set
    End Property
End Class

<Example(StringValue:="This is a string.")> _
Class Class1
    Public Shared Sub Main()
        Dim info As System.Reflection.MemberInfo = GetType(Class1)
        For Each attrib As Object In info.GetCustomAttributes(true)
            Console.WriteLine(attrib)
        Next attrib
    End Sub
End Class

See also