Check if a one or more attributes is applied to this method in CSharp

Description

The following code shows how to check if a one or more attributes is applied to this method.

Example


using System;//from w ww  .j  a v  a 2 s. c  om
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name
    {
        get
        {
            return myName;
        }
    }
}
public class MyClass1
{
    [MyAttribute("This is an example attribute.")]
    public void MyMethod(int i)
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes_IsDefined
{
    public static void Main()
    {
        Type myType = typeof(MyClass1);
        MemberInfo[] myMembers = myType.GetMembers();
        for(int i = 0; i < myMembers.Length; i++)
        {
            if(myMembers[i].IsDefined(typeof(MyAttribute), false))
            {
                Object[] myAttributes = myMembers[i].GetCustomAttributes(typeof(MyAttribute), false);
                Console.WriteLine(myMembers[i]);
                for(int j = 0; j < myAttributes.Length; j++)
                    Console.WriteLine(((MyAttribute)myAttributes[j]).Name);
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type