C# ParameterInfo IsDefined

Description

ParameterInfo IsDefined Determines whether the custom attribute of the specified type or its derived types is applied to this parameter.

Syntax

ParameterInfo.IsDefined has the following syntax.


public virtual bool IsDefined(
  Type attributeType,
  bool inherit
)

Parameters

ParameterInfo.IsDefined has the following parameters.

  • attributeType - The Type object to search for.
  • inherit - This argument is ignored for objects of this type. See Remarks.

Returns

ParameterInfo.IsDefined method returns true if one or more instances of attributeType or its derived types are applied to this parameter; otherwise, false.

Example


/*from  w ww.  j a v a2 s. co  m*/
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Parameter)]
public class MyAttribute : Attribute
{
    private string myName;
    public MyAttribute(string name)
    {
        myName = name;
    }
    public string Name 
    {
        get 
        {
            return myName;
        }
    }
}
[AttributeUsage(AttributeTargets.Parameter)]
public class MyDerivedAttribute : MyAttribute
{
    public MyDerivedAttribute(string name) : base(name) {}
}
public class MyClass1
{
    public void MyMethod(
        [MyAttribute("This is an example parameter attribute")]
        int i,
        [MyDerivedAttribute("This is another parameter attribute")]
        int j,
        int k )
    {
        return;
    }
}

public class MemberInfo_GetCustomAttributes 
{
    public static void Main()
    {
        Type myType = typeof(MyClass1);
        MethodInfo[] myMethods = myType.GetMethods();
        foreach (MethodInfo mi in myMethods)
        {
            ParameterInfo[] myParameters = mi.GetParameters();
            if (myParameters.Length > 0)
            {
                foreach (ParameterInfo pi in myParameters)
                {
                    if (pi.IsDefined(typeof(MyAttribute), false))
                    {
                        Console.WriteLine("Parameter {0}, name = {1}, type = {2}", 
                            pi.Position, pi.Name, pi.ParameterType);
                    }
                }
            }
        }  
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Reflection »




EventInfo
FieldInfo
MemberInfo
MethodInfo
ParameterInfo
TypeInfo