C# FieldInfo IsDefined

Description

FieldInfo IsDefined When overridden in a derived class, indicates whether one or more attributes of the specified type or of its derived types is applied to this member.

Syntax

FieldInfo.IsDefined has the following syntax.


public abstract bool IsDefined(
  Type attributeType,
  bool inherit
)

Parameters

FieldInfo.IsDefined has the following parameters.

  • attributeType - The type of custom attribute to search for. The search includes derived types.
  • inherit - true to search this member's inheritance chain to find the attributes; otherwise, false. This parameter is ignored for properties and events; see Remarks.

Returns

FieldInfo.IsDefined method returns true if one or more instances of attributeType or any of its derived types is applied to this member; otherwise, false.

Example


using System;//from  w w w  .  j  a v  a2s. 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("\nThe attributes of type MyAttribute for the member {0} are: \n",
                    myMembers[i]);
                for(int j = 0; j < myAttributes.Length; j++)
                    Console.WriteLine("The value of the attribute is : \"{0}\"",
                        ((MyAttribute)myAttributes[j]).Name);
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Reflection »




EventInfo
FieldInfo
MemberInfo
MethodInfo
ParameterInfo
TypeInfo