C# Type IsDefined

Description

Type 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

Type.IsDefined has the following syntax.


public abstract bool IsDefined(
  Type attributeType,
  bool inherit
)

Parameters

Type.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

Type.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

The following example determines whether the specified attribute is applied to the specified member.


/*from   w  w w.j  a  va 2 s  .  c o  m*/
using System;
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 MainClass
{
    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]);
            }
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version