.NET Framework Class Library
AttributeGetCustomAttributes Method (MemberInfo, Type)

Retrieves an array of the custom attributes applied to a member of a type. Parameters specify the member, and the type of the custom attribute to search for.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)
Syntax
Public Shared Function GetCustomAttributes ( _
	element As [%$TOPIC/ms130869_en-us_VS_110_1_0_0_0_0%], _
	type As [%$TOPIC/ms130869_en-us_VS_110_1_0_0_0_1%] _
) As [%$TOPIC/ms130869_en-us_VS_110_1_0_0_0_2%]()
public static [%$TOPIC/ms130869_en-us_VS_110_1_0_1_0_0%][] GetCustomAttributes(
	[%$TOPIC/ms130869_en-us_VS_110_1_0_1_0_1%] element,
	[%$TOPIC/ms130869_en-us_VS_110_1_0_1_0_2%] type
)
public:
static array<[%$TOPIC/ms130869_en-us_VS_110_1_0_2_0_0%]^>^ GetCustomAttributes(
	[%$TOPIC/ms130869_en-us_VS_110_1_0_2_0_1%]^ element, 
	[%$TOPIC/ms130869_en-us_VS_110_1_0_2_0_2%]^ type
)
static member GetCustomAttributes : 
        element:[%$TOPIC/ms130869_en-us_VS_110_1_0_3_0_0%] * 
        type:[%$TOPIC/ms130869_en-us_VS_110_1_0_3_0_1%] -> [%$TOPIC/ms130869_en-us_VS_110_1_0_3_0_2%][] 

Parameters

element
Type: System.ReflectionMemberInfo

An object derived from the MemberInfo class that describes a constructor, event, field, method, or property member of a class.

type
Type: SystemType

The type, or a base type, of the custom attribute to search for.

Return Value

Type: SystemAttribute
An Attribute array that contains the custom attributes of type type applied to element, or an empty array if no such custom attributes exist.
Exceptions
ExceptionCondition
ArgumentNullException

element or type is .

ArgumentException

type is not derived from Attribute.

NotSupportedException

element is not a constructor, method, property, event, type, or field.

TypeLoadException

A custom attribute type cannot be loaded.

Remarks

The return value contains the custom attributes for ancestors of element.

NoteNote

Starting with the .NET Framework version 2.0, this method returns security attributes on methods, constructors, and types if the attributes are stored in the new metadata format. Assemblies compiled with version 2.0 or later use the new format. Dynamic assemblies and assemblies compiled with earlier versions of the .NET Framework use the old XML format. See Emitting Declarative Security Attributes.

Examples

The following code example demonstrates the use of GetCustomAttribute, taking a MemberInfo as a parameter.

Imports System
Imports System.Reflection
Imports System.Security
Imports System.Runtime.InteropServices

' Define an enumeration of Win32 unmanaged types 
Public Enum UnmanagedType
    User
    GDI
    Kernel
    Shell
    Networking
    Multimedia
End Enum 'UnmanagedType

' Define the Unmanaged attribute. 
Public Class UnmanagedAttribute 
             Inherits Attribute

    ' Storage for the UnmanagedType value. 
    Protected thisType As UnmanagedType

    ' Set the unmanaged type in the constructor. 
    Public Sub New(ByVal type As UnmanagedType) 
        thisType = type
    End Sub 'New 

    ' Define a property to get and set the UnmanagedType value. 
    Public Property Win32Type() As UnmanagedType 
        Get 
            Return thisType
        End Get 
        Set
            thisType = Win32Type
        End Set 
    End Property 
End Class 'UnmanagedAttribute 

' Create a class for an imported Win32 unmanaged function. 
Public Class Win32
    <DllImport("user32.dll", CharSet:=CharSet.Unicode)> _
    Public Shared Function MessageBox(ByVal hWnd As Integer, _
                                      ByVal Text As String, _
                                      ByVal caption As String, _
                                      ByVal type As Integer) As Integer 
    End Function 'MessageBox
End Class 'Win32

Public Class AClass
    ' Add some attributes to Win32CallMethod.
    <Obsolete("This method is obsolete. Use managed MsgBox instead."), _
     Unmanaged(UnmanagedType.User)>  _
    Public Sub Win32CallMethod() 
        Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0)    
    End Sub 'Win32CallMethod
End Class 'AClass

Class DemoClass
    Shared Sub Main(ByVal args() As String) 
        ' Get the AClass type to access its metadata. 
        Dim clsType As Type = GetType(AClass)
        ' Get the type information for Win32CallMethod. 
        Dim mInfo As MethodInfo = clsType.GetMethod("Win32CallMethod")
        If Not (mInfo Is Nothing) Then 
            ' Iterate through all the attributes of the method. 
            Dim attr As Attribute
            For Each attr In  Attribute.GetCustomAttributes(mInfo)
                ' Check for the Obsolete attribute. 
                If attr.GetType().Equals(GetType(ObsoleteAttribute)) Then
                    Console.WriteLine("Method {0} is obsolete. The message is:", mInfo.Name)
                    Console.WriteLine("  ""{0}""", CType(attr, ObsoleteAttribute).Message)
                ' Check for the Unmanaged attribute. 
                ElseIf attr.GetType().Equals(GetType(UnmanagedAttribute)) Then
                    Console.WriteLine("This method calls unmanaged code.")
                    Console.WriteLine( _
                            String.Format("The Unmanaged attribute type is {0}.", _
                            CType(attr, UnmanagedAttribute).Win32Type))
                    Dim myCls As New AClass()
                    myCls.Win32CallMethod()
                End If 
            Next attr
        End If 
    End Sub 'Main
End Class 'DemoClass

' 
'This code example produces the following results.  
' 
'First, the compilation yields the warning, "...This method is  
'obsolete. Use managed MsgBox instead." 
'Second, execution yields a message box with a title of "Caution!"  
'and message text of "This is an unmanaged call."  
'Third, the following text is displayed in the console window: 
' 
'Method Win32CallMethod is obsolete. The message is: 
'  "This method is obsolete. Use managed MsgBox instead." 
'This method calls unmanaged code. 
'The Unmanaged attribute type is User. 
' 
using System;
using System.Reflection;
using System.Security;
using System.Runtime.InteropServices;

namespace CustAttrs4CS
{

    // Define an enumeration of Win32 unmanaged types 
    public enum UnmanagedType
    {
        User,
        GDI,
        Kernel,
        Shell,
        Networking,
        Multimedia
    }

    // Define the Unmanaged attribute. 
    public class UnmanagedAttribute : Attribute
    {
        // Storage for the UnmanagedType value. 
        protected UnmanagedType thisType;

        // Set the unmanaged type in the constructor. 
        public UnmanagedAttribute(UnmanagedType type)
        {
            thisType = type;
        }

        // Define a property to get and set the UnmanagedType value. 
        public UnmanagedType Win32Type
        {
            get { return thisType; }
            set { thisType = Win32Type; }
        }
    }

    // Create a class for an imported Win32 unmanaged function. 
    public class Win32 {
        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        public static extern int MessageBox(int hWnd, String text,
            String caption, uint type);
    }

    public class AClass {
        // Add some attributes to Win32CallMethod.
        [Obsolete("This method is obsolete. Use managed MsgBox instead.")]
        [Unmanaged(UnmanagedType.User)]
        public void Win32CallMethod()
        {
            Win32.MessageBox(0, "This is an unmanaged call.", "Caution!", 0);
        }
    }

    class DemoClass {
        static void Main(string[] args)
            {
            // Get the AClass type to access its metadata.
            Type clsType = typeof(AClass);
            // Get the type information for Win32CallMethod.
            MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
            if (mInfo != null)
            {
                // Iterate through all the attributes of the method. 
                foreach(Attribute attr in
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the Obsolete attribute. 
                    if (attr.GetType() == typeof(ObsoleteAttribute))
                    {
                        Console.WriteLine("Method {0} is obsolete. " +
                            "The message is:",
                            mInfo.Name);
                        Console.WriteLine("  \"{0}\"",
                            ((ObsoleteAttribute)attr).Message);
                    }

                    // Check for the Unmanaged attribute. 
                    else if (attr.GetType() == typeof(UnmanagedAttribute))
                    {
                        Console.WriteLine(
                            "This method calls unmanaged code.");
                        Console.WriteLine(
                            String.Format("The Unmanaged attribute type is {0}.",
                                          ((UnmanagedAttribute)attr).Win32Type));
                        AClass myCls = new AClass();
                        myCls.Win32CallMethod();
                    }
                }
            }
        }
    }
}

/*

This code example produces the following results.

First, the compilation yields the warning, "...This method is
obsolete. Use managed MsgBox instead."
Second, execution yields a message box with a title of "Caution!"
and message text of "This is an unmanaged call."
Third, the following text is displayed in the console window:

Method Win32CallMethod is obsolete. The message is:
  "This method is obsolete. Use managed MsgBox instead."
This method calls unmanaged code.
The Unmanaged attribute type is User.

*/
using namespace System;
using namespace System::Reflection;
using namespace System::Security;
using namespace System::Runtime::InteropServices;

namespace CustAttrs4CS
{
   // Create a class for Win32 imported unmanaged functions. 
   public ref class Win32
   {
   public:

      [DllImport("user32.dll", CharSet = CharSet::Unicode)]
      static int MessageBox( int hWnd, String^ text, String^ caption, UInt32 type );
   };

   public ref class AClass
   {
   public:

      // Add some attributes to the Win32CallMethod.

      [Obsolete("This method is obsolete. Use managed MsgBox instead.")]
      void Win32CallMethod()
      {
         Win32::MessageBox( 0, "This is an unmanaged call.", "Be Careful!", 0 );
      }

   };

   ref class DemoClass
   {
   public:
      static void Main()
      {
         // Get the Class type to access its metadata.
         Type^ clsType = AClass::typeid;

         // Get the type information for the Win32CallMethod.
         MethodInfo^ mInfo = clsType->GetMethod( "Win32CallMethod" );
         if ( mInfo != nullptr )
         {
            // Iterate through all the attributes for the method.
            System::Collections::IEnumerator^ myEnum3 = Attribute::GetCustomAttributes( mInfo )->GetEnumerator();
            while ( myEnum3->MoveNext() )
            {
               Attribute^ attr = safe_cast<Attribute^>(myEnum3->Current);

               // Check for the Obsolete attribute. 
               if ( attr->GetType() == ObsoleteAttribute::typeid )
               {
                  Console::WriteLine( "Method {0} is obsolete. " 
                  "The message is:", mInfo->Name );
                  Console::WriteLine( (dynamic_cast<ObsoleteAttribute^>(attr))->Message );
               }
               // Check for the SuppressUnmanagedCodeSecurity attribute. 
               else 

               // Check for the SuppressUnmanagedCodeSecurity attribute. 
               if ( attr->GetType() == SuppressUnmanagedCodeSecurityAttribute::typeid )
               {
                  Console::WriteLine( "This method calls unmanaged code " 
                  "with no security check." );
                  Console::WriteLine( "Please do not use unless absolutely necessary." );
                  AClass^ myCls = gcnew AClass;
                  myCls->Win32CallMethod();
               }
            }
         }
      }
   };
}


/*
 * Output:
 * Method Win32CallMethod is obsolete. The message is:
 * This method is obsolete. Use managed MsgBox instead.
 * This method calls unmanaged code with no security check.
 * Please do not use unless absolutely necessary.
 */
Version Information

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1
Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.