Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Attribute.GetCustomAttributes Method (MemberInfo, Boolean)

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

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public static Attribute[] GetCustomAttributes (
	MemberInfo element,
	bool inherit
)
public static Attribute[] GetCustomAttributes (
	MemberInfo element, 
	boolean inherit
)
public static function GetCustomAttributes (
	element : MemberInfo, 
	inherit : boolean
) : Attribute[]
Not applicable.

Parameters

element

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

inherit

If true, specifies to also search the ancestors of element for custom attributes.

Return Value

An Attribute array that contains the custom attributes applied to element, or an empty array if no such custom attributes exist.

Exception typeCondition

ArgumentNullException

element is a null reference (Nothing in Visual Basic).

NotSupportedException

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

TypeLoadException

A custom attribute type cannot be loaded.

The return value contains the custom attributes for ancestors of element if inherit is true.

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.

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

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")]
        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.
 
*/


package CustAttrs4JSL; 
import System.*;
import System.Reflection.*;
import System.Security.*;
import System.Runtime.InteropServices.*;

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

// Define the Unmanaged attribute.
public class UnmanagedAttribute extends Attribute
{
    // Storage for the UnmanagedType value.
    private 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 get_thisType()
   {
      return thisType;
   }

   public void set_thisType(UnmanagedType Win32Type)
   {   
      thisType = Win32Type;
   }
}

// Create a class for Win32 imported unmanaged functions.
public class Win32
{
    /** @attribute DllImport("user32.dll")
     */
    public static native int MessageBox(int hWnd, String text, 
        String caption, UInt32 type);
} //Win32

public class AClass
{
    // Add some attributes to the Win32CallMethod.
    /** @attribute Obsolete("This method is obsolete."
            + "Use managed MsgBox instead.")
     */
    public void Win32CallMethod()
    {
        Win32.MessageBox(0, "This is an unmanaged call.", "Be Careful!", 
            (UInt32)0);
    } //Win32CallMethod
} //AClass

class DemoClass
{
    public static void main(String[] args)
    {
        // Get the Class type to access its metadata.
        Type clsType = AClass.class.ToType();
        // Get the type information for the Win32CallMethod.
        MethodInfo mInfo = clsType.GetMethod("Win32CallMethod");
        if (mInfo != null) {
            // Iterate through all the attributes for the method.
            for (int iCtr = 0; iCtr < Attribute.GetCustomAttributes(mInfo).
                get_Length(); iCtr++) {
                Attribute attr = (Attribute)Attribute.
                    GetCustomAttributes(mInfo).get_Item(iCtr);
                // Check for the Obsolete attribute.
                if (attr.GetType().Equals(ObsoleteAttribute.class.ToType())) {
                    Console.WriteLine("Method {0} is obsolete. " +
                        "The message is:", mInfo.get_Name());
                    Console.WriteLine(((ObsoleteAttribute)attr).get_Message());
                }
                // Check for the SuppressUnmanagedCodeSecurity attribute.
                else {
                    if (attr.GetType().Equals(
                        SuppressUnmanagedCodeSecurityAttribute.class.
                        ToType())) {
                        Console.WriteLine("This method calls unmanaged code " 
                            + "with no security check.");
                        Console.WriteLine("Please do not use unless absolutely"
                            +" necessary.");
                        AClass myCls = new AClass();
                        myCls.Win32CallMethod();
                    }
                }
            }
        }
    } //main
} //DemoClass   

/*
    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.
*/

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

Show:
© 2014 Microsoft