System.Reflection.PropertyInfo Class

Assembly: Mscorlib.dll
Namespace: System.Reflection
Summary
Discovers the attributes of a property and provides access to property metadata.
C# Syntax:
[Serializable]
public abstract class PropertyInfo : MemberInfo
Thread Safety
This type is safe for multithreaded operations.
Remarks
Properties are logically the same as fields. A property is a named aspect of an object's state whose value is typically accessible through get and set accessors. Properties may be read-only, in which case a set routine is not supported.

Several methods in this class assume that the getter and setter methods of a property have certain formats. The signatures of the get and set methods must match the following convention:

If this format is not followed, the behavior of the GetValue and SetValue methods is undefined.

Calling ICustomAttributeProvider.GetCustomAttributes on PropertyInfo when the inherit parameter of GetCustomAttributes is true does not walk the type hierarchy. Use Attribute to inherit custom attributes.



Notes to inheritors: When you inherit from PropertyInfo, you must override the following members: PropertyInfo.GetValue, PropertyInfo.SetValue, PropertyInfo.GetAccessors, PropertyInfo.GetGetMethod, PropertyInfo.GetSetMethod, and PropertyInfo.GetIndexParameters.
See also:
System.Reflection Namespace

System.Reflection.PropertyInfo Member List:

Public Properties
Attributes Read-only

Gets the attributes for this property.
CanRead Read-only

Gets a value indicating whether the property can be read.
CanWrite Read-only

Gets a value indicating whether the property can be written to.
DeclaringType
(inherited from System.Reflection.MemberInfo)
Read-only

See base class member description: System.Reflection.MemberInfo.DeclaringType


Gets the class that declares this member.
IsSpecialName Read-only

Gets a value indicating whether the property is the special name.
MemberType Read-only

Overridden:
Gets the Type of property reflected by this PropertyInfo object.
Name
(inherited from System.Reflection.MemberInfo)
Read-only

See base class member description: System.Reflection.MemberInfo.Name


Gets the name of this member.
PropertyType Read-only

Gets the type of the field of this property.
ReflectedType
(inherited from System.Reflection.MemberInfo)
Read-only

See base class member description: System.Reflection.MemberInfo.ReflectedType


Gets the class object that was used to obtain this instance of MemberInfo.
Public Methods
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetAccessors Overloaded:
GetAccessors()

Returns an array of the public get and set accessors on this property, and any method associated with this property.
GetAccessors Overloaded:
GetAccessors(bool nonPublic)

Returns an array of the public and/or non-public get and set accessors on this property.
GetCustomAttributes
(inherited from System.Reflection.MemberInfo)
Overloaded:
GetCustomAttributes(bool inherit)

See base class member description: System.Reflection.MemberInfo.GetCustomAttributes


When overridden in a derived class, returns an array of all of the custom attributes.
GetCustomAttributes
(inherited from System.Reflection.MemberInfo)
Overloaded:
GetCustomAttributes(Type attributeType, bool inherit)

See base class member description: System.Reflection.MemberInfo.GetCustomAttributes


When overridden in a derived class, returns an array of custom attributes identified by Type.
GetGetMethod Overloaded:
GetGetMethod()

Returns the public get accessor for this property.
GetGetMethod Overloaded:
GetGetMethod(bool nonPublic)

When overridden in a derived class, returns the public or non-public get accessor for this property.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetIndexParameters When overridden in a derived class, returns an array of all the index parameters for the property.
GetSetMethod Overloaded:
GetSetMethod()

Returns the public set accessor for this property.
GetSetMethod Overloaded:
GetSetMethod(bool nonPublic)

When overridden in a derived class, returns the set accessor for this property.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
GetValue Overloaded:
GetValue(object obj, object[] index)

Returns the value of the property with optional index values for indexed properties.
GetValue Overloaded:
GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)

When overridden in a derived class, returns the value of a property having the specified binding, index, and CultureInfo.
IsDefined
(inherited from System.Reflection.MemberInfo)
See base class member description: System.Reflection.MemberInfo.IsDefined


When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member.
SetValue Overloaded:
SetValue(object obj, object value, object[] index)

Sets the value of the property with optional index values for index properties.
SetValue Overloaded:
SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture)

When overridden in a derived class, sets the property value for the given object to the given value.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Constructors
ctor #1 Default constructor. This constructor is called by derived class constructors to initialize state in this type.
Initializes a new instance of the PropertyInfo class.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Reflection.PropertyInfo Member Details

ctor #1
Summary
Initializes a new instance of the PropertyInfo class.

Default constructor. This constructor is called by derived class constructors to initialize state in this type.
C# Syntax:
protected PropertyInfo();

Return to top


Property: Attributes (read-only)
Summary
Gets the attributes for this property.
C# Syntax:
public abstract PropertyAttributes Attributes {get;}
Remarks
This property represents the attributes associated with a member. All members have a set of attributes that are defined in relation to the specific type of member. The property attributes let the user know if this property is the default property, a SpecialName property, and so on.

To get the Attributes property, first get the class type. From the type, get the PropertyInfo. From the PropertyInfo, get the attributes.

Example
 //Make a property, then display the PropertyInfo
 using System;
 using System.Reflection;
 
 public class Myproperty
 {
    private string caption = "Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
  
 class Mypropertyinfo
 {
    public static int Main(string[] args)
    {
       Console.WriteLine("\nReflection.PropertyInfo");
  
       //Build a property
       Myproperty Myproperty = new Myproperty();
       Console.Write("\nMyproperty.Caption = " + Myproperty.Caption);
  
       //Get the type and PropertyInfo
       Type MyType = Type.GetType("Myproperty");
       PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");
  
       //Get and display the attributes property
       PropertyAttributes Myattributes = Mypropertyinfo.Attributes;
      
       Console.Write("\nPropertyAttributes - " + Myattributes.ToString());
  
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 Myproperty.Caption = Default caption
 PropertyAttributes - None
 */

    

Return to top


Property: CanRead (read-only)
Summary
Gets a value indicating whether the property can be read.
C# Syntax:
public abstract bool CanRead {get;}
Remarks
If the property does not have a get accessor, it cannot be read.

To get the CanRead property, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, get the CanRead value.

Example
In the following example, two properties are created. The first property is readable and the CanRead property is true. The second property is not readable (there is no get accessor), and the CanRead property is false.
using System;
using System.Reflection;
 
//Make two properties, one readable and on not readable
 public class Mypropertya
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 public class Mypropertyb
 {
    private string caption = "B Default caption";
    public string Caption{
       set{if(caption!=value) {caption = value;}
       }
    }
 }
  
 class Mypropertyinfo
 {
    public static int Main()
    {
       Console.WriteLine("\nReflection.PropertyInfo");
  
       //Build two properties
       Mypropertya Mypropertya = new Mypropertya();
       Mypropertyb Mypropertyb = new Mypropertyb();
  
       Console.Write("\nMypropertya.Caption = " + Mypropertya.Caption);
       //Note: Mypropertyb.Caption cannot be read as
       // there is no get accessor
  
       //Get the type and PropertyInfo
       Type MyTypea = Type.GetType("Mypropertya");
       PropertyInfo Mypropertyinfoa = MyTypea.GetProperty("Caption");
       Type MyTypeb = Type.GetType("Mypropertyb");
       PropertyInfo Mypropertyinfob = MyTypeb.GetProperty("Caption");
  
       //Get and display the CanRead property
      
       Console.Write("\nCanRead a - " + Mypropertyinfoa.CanRead);
      
       Console.Write("\nCanRead b - " + Mypropertyinfob.CanRead);
  
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 Mypropertya.Caption = A Default caption
 CanRead a - True
 CanRead b - False
 */

    

Return to top


Property: CanWrite (read-only)
Summary
Gets a value indicating whether the property can be written to.
C# Syntax:
public abstract bool CanWrite {get;}
Remarks
If the property does not have a set accessor, it cannot be written to.

To get the CanWrite property, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, get the CanWrite value.

Example
In the following example, two properties are created. The first property is writable and the CanWrite property is true. The second property is not writable (there is no set accessor), and the CanWrite property is false.
 using System;
 using System.Reflection;
 
 //Make two properties, one writable and one not writable 
 public class Mypropertya
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 public class Mypropertyb
 {
    private string caption = "B Default caption";
    public string Caption{
       get{return caption;}
    }
 }
  
 class Mypropertyinfo
 {
    public static int Main()
    {
       Console.WriteLine("\nReflection.PropertyInfo");
  
       //Build two properties
       Mypropertya Mypropertya = new Mypropertya();
       Mypropertyb Mypropertyb = new Mypropertyb();
  
       //Read and display the property
       Console.Write("\nMypropertya.Caption = " + Mypropertya.Caption);
       Console.Write("\nMypropertyb.Caption = " + Mypropertyb.Caption);
  
       //Write to the property
       Mypropertya.Caption = "A- I have been changed";
       //Note: Mypropertyb.Caption cannot be written as
       // there is no set accessor
  
       //Read and display the property
       Console.Write("\nMypropertya.Caption = " + Mypropertya.Caption);
       Console.Write ("\nMypropertyb.Caption = " + Mypropertyb.Caption);
  
       //Get the type and PropertyInfo
       Type MyTypea = Type.GetType("Mypropertya");
       PropertyInfo Mypropertyinfoa = MyTypea.GetProperty("Caption");
       Type MyTypeb = Type.GetType("Mypropertyb");
       PropertyInfo Mypropertyinfob = MyTypeb.GetProperty("Caption");
  
       //Get and display the CanWrite property
      
       Console.Write("\nCanWrite a - " + Mypropertyinfoa.CanWrite);
      
       Console.Write("\nCanWrite b - " + Mypropertyinfob.CanWrite);
  
       return 0;
    }
 }
 /*
 This code produces the following output:
 
 Reflection.PropertyInfo
 
 Mypropertya.Caption = A Default caption
 Mypropertyb.Caption = B Default caption
 Mypropertya.Caption = A- I have been changed
 Mypropertyb.Caption = B Default caption
 CanWrite a - True
 CanWrite b - False
 */

    

Return to top


Property: DeclaringType (read-only)
Inherited
See base class member description: System.Reflection.MemberInfo.DeclaringType

Summary
Gets the class that declares this member.
C# Syntax:
public abstract Type DeclaringType {get;}
Remarks
The DeclaringType property retrieves a reference to the Type object for the type that declares this member. A member of a class (or interface) is either declared or inherited from a base class (or interface). The returned class might not be the same as the Type object used to obtain this MemberInfo object.
Example
The following example shows how DeclaringType works with classes and interfaces.

 interface i {
 int MyVar() ;
 };
 // DeclaringType for MyVar is i.
 
 class A : i {
 public int MyVar() { return 0; }
 };
 // DeclaringType for MyVar is A.
 
 class B : A {
 new int MyVar() { return 0; }
 };
 // DeclaringType for MyVar is B.
 
 class C : A {
 };
 // DeclaringType for MyVar is A.

    

The following example uses DeclaringType to retrieve the member names of the System.IO.BufferedStream class, along with the class in which those members are declared.

 using System;
 using System.IO;
 using System.Reflection;
 
 class Mymemberinfo { 
 
   public static void Main(string[] args) { 
 
    Console.WriteLine ("\nReflection.MemberInfo");
 
    //Get the Type and MemberInfo. 
    Type MyType =Type.GetType("System.IO.BufferedStream");
    MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
 
    //Get and display the DeclaringType method. 
    Console.Write("\nThere are {0} members in ", Mymemberinfoarray.Length); 
    Console.Write("{0}.", MyType.FullName); 
 
    foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) {  
      Console.Write("\n" + Mymemberinfo.Name + " declaring type - "
        + Mymemberinfo.DeclaringType); 
    }
   }
 }

    

This code produces the following output:

Reflection.MemberInfo

There are 31 members in System.IO.BufferedStream.

WriteByte declaring type - System.IO.BufferedStream

Write declaring type - System.IO.BufferedStream

ReadByte declaring type - System.IO.BufferedStream

Read declaring type - System.IO.BufferedStream

SetLength declaring type - System.IO.BufferedStream

Seek declaring type - System.IO.BufferedStream

EndWrite declaring type - System.IO.Stream

BeginWrite declaring type - System.IO.Stream

EndRead declaring type - System.IO.Stream

BeginRead declaring type - System.IO.Stream

Flush declaring type - System.IO.BufferedStream

Close declaring type - System.IO.BufferedStream

set_Position declaring type - System.IO.BufferedStream

get_Position declaring type - System.IO.BufferedStream

get_Length declaring type - System.IO.BufferedStream

get_CanWrite declaring type - System.IO.BufferedStream

get_CanSeek declaring type - System.IO.BufferedStream

get_CanRead declaring type - System.IO.BufferedStream

InitializeLifetimeService declaring type - System.MarshalByRefObject

GetHashCode declaring type - System.Object

Equals declaring type - System.Object

ToString declaring type - System.Object

GetLifetimeService declaring type - System.MarshalByRefObject

GetType declaring type - System.Object

.ctor declaring type - System.IO.BufferedStream

.ctor declaring type - System.IO.BufferedStream

CanRead declaring type - System.IO.BufferedStream

CanWrite declaring type - System.IO.BufferedStream

CanSeek declaring type - System.IO.BufferedStream

Length declaring type - System.IO.BufferedStream

Position declaring type - System.IO.BufferedStream



Note DeclaringType returns only the member names and the names of their declaring types. To return the member names with their prototypes, call MemberInfo.ToString.

In the following code example, when B overrides virtual method M from A, it essentially redefines (or redeclares) this method. Therefore, B.M's MethodInfo reports the declaring type as B rather than A, even though A is where this method was originally declared.

class A {
    virtual public void M () {}
}
class B: A {
    override public void M () {}
}

    

Return to top


Property: IsSpecialName (read-only)
Summary
Gets a value indicating whether the property is the special name.
C# Syntax:
public bool IsSpecialName {get;}
Remarks
The SpecialName bit is set to flag members that are treated in a special way by some compilers (such as property accessors and operator overloading methods).

To get the IsSpecialName property, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, get the IsSpecialName value.

Return to top


Overridden Property: MemberType (read-only)
Summary
Gets the Type of property reflected by this PropertyInfo object.
C# Syntax:
public override MemberTypes MemberType {get;}
Remarks
MemberType is a derived class of MemberInfo and specifies the type of member this is. Member types are constructors, properties, fields, and methods. Since this is a PropertyInfo property, the returned type is a property.

To get the MemberType property, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, get the MemberType value.

Example
 using System;
 using System.Reflection;
 
 class Mypropertyinfo
 {
    public static int Main()
    {
       Console.WriteLine("\nReflection.PropertyInfo");
  
       //Get the type and PropertyInfo
       Type MyType = Type.GetType("System.Reflection.MemberInfo");
       PropertyInfo Mypropertyinfo = MyType.GetProperty("Name");
  
       //Read and display the MemberType property
       Console.Write("\nMemberType = " + Mypropertyinfo.MemberType.ToString());
  
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 MemberType = Property
 */

    

Return to top


Property: Name (read-only)
Inherited
See base class member description: System.Reflection.MemberInfo.Name

Summary
Gets the name of this member.
C# Syntax:
public abstract string Name {get;}
Remarks
Only the simple name is returned, not the fully qualified name. For example, for a member System.Reflection.MemberTypes.Field, the Name property would be Field.

To get the Name property, get the class Type. From the Type, get the MemberInfo array. From a MemberInfo element of the array, obtain the Name property.

Example
This example lists the Name and DeclaringType property of each member of the System.Empty class.
using System;
using System.Reflection;
 
class Mymemberinfo
 {
    public static int Main()
    {
       Console.WriteLine ("\nReflection.MemberInfo");
       
       //Get the Type and MemberInfo.
       Type MyType = Type.GetType("System.Empty");
       MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
  
       //Get and display the DeclaringType method.
       Console.Write("\nThere are {0} members in ",
          Mymemberinfoarray.GetLength(0));
       Console.Write("{0}.", MyType.FullName);
  
       foreach (MemberInfo Mymemberinfo in Mymemberinfoarray)
       {
          Console.Write("\n" + Mymemberinfo.Name
             + " declaring type - " +
              Mymemberinfo.DeclaringType);
       }
  
       return 0;
    }
 }
 /*
 This code produces the following output:

Reflection.MemberInfo

There are 6 members in System.Empty.
Value declaring type - System.Empty
GetObjectData declaring type - System.Empty
GetHashCode declaring type - System.Object
Equals declaring type - System.Object
ToString declaring type - System.Empty
GetType declaring type - System.Object
 */

    

Return to top


Property: PropertyType (read-only)
Summary
Gets the type of the field of this property.
C# Syntax:
public abstract Type PropertyType {get;}
Remarks
The Type is String, Boolean, Int32, and so on.

To get the PropertyType property, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, get the PropertyType value.

Example
using System;
using System.Reflection;
 
class Mypropertyinfo
 {
    public static int Main()
    {
       Console.WriteLine("\nReflection.PropertyInfo");
  
       //Get the type and PropertyInfo
       Type MyTypea = Type.GetType("System.Reflection.MemberInfo");
       PropertyInfo Mypropertyinfoa = MyTypea.GetProperty("Name");
       Type MyTypeb = Type.GetType("System.Reflection.MethodBase");
       PropertyInfo Mypropertyinfob = MyTypeb.GetProperty("IsFinal");
  
       //Read and display the PropertyType property
       Console.Write ("\n" + MyTypea.FullName + "." + Mypropertyinfoa.Name +
          " has a PropertyType of " + Mypropertyinfoa.PropertyType);
       Console.Write("\n" + MyTypeb.FullName + "." + Mypropertyinfob.Name +
          " has a PropertyType of " + Mypropertyinfob.PropertyType);
  
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 System.Reflection.MemberInfo.Name has a PropertyType of System.String
 System.Reflection.MethodBase.IsFinal has a PropertyType of Boolean
 */

    

Return to top


Property: ReflectedType (read-only)
Inherited
See base class member description: System.Reflection.MemberInfo.ReflectedType

Summary
Gets the class object that was used to obtain this instance of MemberInfo.
C# Syntax:
public abstract Type ReflectedType {get;}
Remarks
The ReflectedType property retrieves the Type object that was used to obtain this instance of MemberInfo. A MemberInfo object represents a member of a particular class or interface.

In order to obtain a MethodInfo object:

Example
 using System;
 using System.IO;
 using System.Reflection;
 
 class Mymemberinfo { 
 
   public static void Main(string[] args) { 
 
    Console.WriteLine ("\nReflection.MemberInfo");
 
    //Get the Type and MemberInfo  
    Type MyType =Type.GetType("System.IO.BufferedStream"); 
    MemberInfo[] Mymemberinfoarray = MyType.GetMembers(); 
 
    //Get and display the DeclaringType method 
    Console.Write("\nThere are {0} members in ", Mymemberinfoarray.Length); 
    Console.Write("{0}.", MyType.FullName); 
 
    foreach (MemberInfo Mymemberinfo in Mymemberinfoarray) { 
      Console.Write("\n" + Mymemberinfo.Name + " reflected type - " +
         Mymemberinfo.ReflectedType);
    }
   }
 }

    
This code produces the following output:

Reflection.MemberInfo

There are 31 members in System.IO.BufferedStream.

WriteByte reflected type - System.IO.BufferedStream

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~PropertyInfo();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: GetAccessors()
Summary
Returns an array of the public get and set accessors on this property, and any method associated with this property.
C# Syntax:
public MethodInfo[] GetAccessors();
Return Value:
An array of type MethodInfo containing the public get and set accessors, or an empty array if public accessors do not exist on this property.

Return to top


Overloaded Method: GetAccessors(
   bool nonPublic
)
Summary
Returns an array of the public and/or non-public get and set accessors on this property.
C# Syntax:
public abstract MethodInfo[] GetAccessors(
   bool nonPublic
);
Parameters:

nonPublic

Indicates whether non-public methods should be returned in the MethodInfo array.true if non-public methods are to be included; otherwise, false.

Return Value:
An array of type MethodInfo containing the matching public or non-public accessors, or an empty array if matching accessors do not exist on this property.
Remarks
To use the GetAccessors method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetAccessors method.
Example
 using System;
 using System.Reflection;
 
 //Make a property
 public class Myproperty   
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 
 class Mypropertyinfo
 {
    public static int Main()
       {
       Console.WriteLine ("\nReflection.PropertyInfo");
 
       //Get the type and PropertyInfo
       Type MyType = Type.GetType("Myproperty");
       PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");
 
       //Get the public GetAccessors Method
       MethodInfo[] Mymethodinfoarray = Mypropertyinfo.GetAccessors(true);
       Console.Write ("\nThere are "
          + Mymethodinfoarray.Length + "accessors (public)");
       
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 There are 2 accessors (public)
 */

    

Return to top


Overloaded Method: GetCustomAttributes(
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.GetCustomAttributes

Summary
When overridden in a derived class, returns an array of all of the custom attributes.
C# Syntax:
public abstract object[] GetCustomAttributes(
   bool inherit
);
Parameters:

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
An array of all the custom attributes, or an array with zero elements if no attributes are defined.
Implements:
ICustomAttributeProvider.GetCustomAttributes
Example

using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
   private string myName;
   public MyAttribute(string name)
   {
      myName = name;
   }
   public string Name
   {
      get
      {
         return myName;
      }
   }
}

// Define a class which has the custom attribute associated with one of its members.
public class MyClass1
{
   [MyAttribute("This is an example attribute")]
   public void MyMethod(int i)
   {
      return;
   }
}

public class MemberInfo_GetCustomAttributes
{
   public static void Main()
   {
      try
      {
         // Get the type of the class 'MyClass1'.
         Type myType = typeof(MyClass1);
         // Get the members associated with the class 'MyClass1'.
         MemberInfo[] myMembers = myType.GetMembers();

         // Display the attributes for each of the members of the class 'MyClass1'.
         for(int i = 0; i < myMembers.Length; i++)
         {
            Object[] myAttributes = myMembers[i].GetCustomAttributes(false);
            if(myAttributes.Length > 0)
            {
               Console.WriteLine("\nThe attributes for the member {0} are : \n", myMembers[i]);
               for(int j = 0; j < myAttributes.Length; j++)
                  Console.WriteLine("The type of the attribute is : {0}", myAttributes[j]);
            }
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception Caught! "+e.Message);
      }
   }
}

    
See also:
Object | CustomAttributeBuilder

Return to top


Overloaded Method: GetCustomAttributes(
   Type attributeType,
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.GetCustomAttributes

Summary
When overridden in a derived class, returns an array of custom attributes identified by Type.
C# Syntax:
public abstract object[] GetCustomAttributes(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The type of attribute to search for. Only attributes that are assignable to this type are returned.

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
An array of custom attributes defined on this reflected member, or an array with zero (0) elements if no attributes are defined.
Exceptions
Exception Type Condition
TypeLoadException If the custom attribute type can not be loaded.
Implements:
ICustomAttributeProvider.GetCustomAttributes

Return to top


Overloaded Method: GetGetMethod()
Summary
Returns the public get accessor for this property.
C# Syntax:
public MethodInfo GetGetMethod();
Return Value:
A MethodInfo object representing the public get accessor for this property, or null if the get accessor is non-public or does not exist.
Remarks
This is a convenience method that provides an implementation for the abstract GetGetMethod method with the nonPublic parameter set to false.

To use the GetGetMethod method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetGetMethod method.

Return to top


Overloaded Method: GetGetMethod(
   bool nonPublic
)
Summary
When overridden in a derived class, returns the public or non-public get accessor for this property.
C# Syntax:
public abstract MethodInfo GetGetMethod(
   bool nonPublic
);
Parameters:

nonPublic

Indicates whether non-public get accessors should be returned.true if non-public methods are to be included; otherwise, false.

Return Value:
A MethodInfo object representing the get accessor for this property, if nonPublic is true. Returns null if nonPublic is false and the get accessor is non-public, or if nonPublic is true but no get accessors exist.
Exceptions
Exception Type Condition
SecurityException The requested method is not public and the caller does not have ReflectionPermission to reflect on methods that are not public.
Remarks
This property is the MethodInfo representing the get accessor.

To use the GetGetMethod method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetGetMethod method.

Example
 using System;
 using System.Reflection;
 
 //Make a property
 public class Myproperty   
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 
 class Mypropertyinfo
 {
    public static int Main()
       {
       Console.WriteLine ("\nReflection.PropertyInfo");
 
       //Get the type and PropertyInfo for two separate properties
       Type MyTypea = Type.GetType("Myproperty");
       PropertyInfo Mypropertyinfoa = MyTypea.GetProperty("Caption");
       Type MyTypeb = Type.GetType("System.Reflection.MethodInfo");
       PropertyInfo Mypropertyinfob = MyTypeb.GetProperty("MemberType");
 
       //Get and display the GetGetMethod Method for each property
       MethodInfo Mygetmethodinfoa = Mypropertyinfoa.GetGetMethod();
       Console.Write ("\nGetAccessor for " + Mypropertyinfoa.Name
          + " returns a " + Mygetmethodinfoa.ReturnType);
       MethodInfo Mygetmethodinfob = Mypropertyinfob.GetGetMethod();
       Console.Write ("\nGetAccessor for " + Mypropertyinfob.Name
          + " returns a " + Mygetmethodinfob.ReturnType);
 
       //Display the GetGetMethod without using the MethodInfo
       Console.Write ("\n" + MyTypea.FullName + "." + Mypropertyinfoa.Name
           + " GetGetMethod - " + Mypropertyinfoa.GetGetMethod());
       Console.Write ("\n" + MyTypeb.FullName + "." + Mypropertyinfob.Name
           + " GetGetMethod - " + Mypropertyinfob.GetGetMethod());
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 GetAccessor for Caption returns a System.String
 GetAccessor for MemberType returns a System.Reflection.MemberTypes
 Myproperty.Caption GetGetMethod - System.String get_Caption()
 System.Reflection.MethodInfo.MemberType GetGetMethod - System.Reflection.MemberTypes get_MemberType()
*/

    
.NET Framework Security:
ReflectionPermission for reflecting methods that are not public. Associated enumeration: ReflectionPermissionFlag.TypeInformation

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetIndexParameters()
Summary
When overridden in a derived class, returns an array of all the index parameters for the property.
C# Syntax:
public abstract ParameterInfo[] GetIndexParameters();
Return Value:
An array of type ParameterInfo containing the parameters for the indexes.
Exceptions
Exception Type Condition
SecurityException The property itself is accessible, but the get or set accessor is not.
Remarks
Extract any required parameter information from the returned array.

To use the GetIndexParameters method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetIndexParameters method.

Example
using System;
using System.Reflection;
 
//Make a property
 public class Myproperty   
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 
 class Mypropertyinfo
 {
    public static int Main()
       {
       Console.WriteLine ("\nReflection.PropertyInfo");
 
       //Get the type and PropertyInfo
       Type MyType = Type.GetType("Myproperty");
       PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");
 
       //Get the public GetIndexParameters Method
       ParameterInfo[] Myparameterinfoarray =
          Mypropertyinfo.GetIndexParameters();
       Console.Write ("\n" + MyType.FullName + "." + Mypropertyinfo.Name
          + " has " + Myparameterinfoarray.GetLength(0) + " parameters");
 
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 Myproperty.Caption has 0 parameters
 */

    
.NET Framework Security:
ReflectionPermission for reflecting objects that are not visible. Associated enumeration: ReflectionPermissionFlag.TypeInformation

Return to top


Overloaded Method: GetSetMethod()
Summary
Returns the public set accessor for this property.
C# Syntax:
public MethodInfo GetSetMethod();
Return Value:
The MethodInfo object representing the Set method for this property if the set accessor is public, or null if the set accessor is not public.
Remarks
This is a convenience method that provides an implementation for the abstract GetSetMethod method with the nonPublic parameter set to false.

To use the GetSetMethod method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetSetMethod method.

Return to top


Overloaded Method: GetSetMethod(
   bool nonPublic
)
Summary
When overridden in a derived class, returns the set accessor for this property.
C# Syntax:
public abstract MethodInfo GetSetMethod(
   bool nonPublic
);
Parameters:

nonPublic

Indicates whether the accessor should be returned if it is non-public.true if non-public methods are to be included; otherwise, false.

Return Value:


Value Condition
A MethodInfo object representing the Set method for this property. The set accessor is public.nonPublic is true and non-public methods can be returned.
null nonPublic is true, but the property is read-only. -or- nonPublic is false and the set accessor is non-public. -or- There is no set accessor.
Exceptions
Exception Type Condition
SecurityException The requested method is not public and the caller does not have ReflectionPermission to reflect on methods that are not public.
Remarks
To use the GetSetMethod method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetSetMethod method.
Example
using System;
using System.Reflection;
 
//Make a property
 public class Myproperty   
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 
 class Mypropertyinfo
 {
    public static int Main()
       {
       Console.WriteLine ("\nReflection.PropertyInfo");
 
       //Get the type and PropertyInfo for two separate properties
       Type MyTypea = Type.GetType("Myproperty");
       PropertyInfo Mypropertyinfoa = MyTypea.GetProperty("Caption");
       Type MyTypeb = Type.GetType("System.Text.StringBuilder");
       PropertyInfo Mypropertyinfob = MyTypeb.GetProperty("Length");
       //Get and display the GetSetMethod Method for each property
       MethodInfo Mygetmethodinfoa = Mypropertyinfoa.GetSetMethod();
       Console.Write ("\nSetAccessor for " + Mypropertyinfoa.Name
          + " returns a " + Mygetmethodinfoa.ReturnType);
       MethodInfo Mygetmethodinfob = Mypropertyinfob.GetSetMethod();
       Console.Write ("\nSetAccessor for " + Mypropertyinfob.Name
          + " returns a " + Mygetmethodinfob.ReturnType);
 
       //Display the GetSetMethod without using the MethodInfo
       Console.Write ("\n\n" + MyTypea.FullName + "."
          + Mypropertyinfoa.Name + " GetSetMethod - "
          + Mypropertyinfoa.GetSetMethod());
       Console.Write ("\n" + MyTypeb.FullName + "."
          + Mypropertyinfob.Name + " GetSetMethod - "
          + Mypropertyinfob.GetSetMethod());
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 SetAccessor for Caption returns a System.Void
 SetAccessor for Length returns a System.Void
 Myproperty.Caption GetSetMethod - Void set_Caption(System.String)
 System.Text.StringBuilder.Length GetSetMethod - Void set_Length(Int32)
 */

    
.NET Framework Security:
ReflectionPermission for reflecting methods that are not public. Associated enumeration: ReflectionPermissionFlag.TypeInformation

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: GetValue(
   object obj,
   object[] index
)
Summary
Returns the value of the property with optional index values for indexed properties.
C# Syntax:
public virtual object GetValue(
   object obj,
   object[] index
);
Parameters:

obj

The object whose property value will be returned.

index

Optional index values for indexed properties. This value should be null for non-indexed properties.

Return Value:
The property value for the obj parameter.
Exceptions
Exception Type Condition
ArgumentException The index array does not contain the type of arguments needed.

-or-

The property's Get method is not found.

TargetException The object does not match the target type, or a property is an instance property but obj is null.
TargetParameterCountException The number of parameters in index does not match the number of parameters the indexed property takes.
MethodAccessException There was an illegal attempt to access a private or protected method inside a class.
Remarks
This is a convenience method that provides an implementation for the abstract GetValue method with a BindingFlags parameter of DefaultChangeType, the Binder set to null, and the CultureInfo set to null.

Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument. For example, use the following code to get the static CurrentCulture property of CultureInfo:

PropertyInfo CurCultProp = (typeof(CultureInfo)).GetProperty("CurrentCulture");

Console.WriteLine("CurrCult: " + CurCultProp.GetValue(null,null));

To use the GetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetValue method.

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation

Return to top


Overloaded Method: GetValue(
   object obj,
   BindingFlags invokeAttr,
   Binder binder,
   object[] index,
   CultureInfo culture
)
Summary
When overridden in a derived class, returns the value of a property having the specified binding, index, and CultureInfo.
C# Syntax:
public abstract object GetValue(
   object obj,
   BindingFlags invokeAttr,
   Binder binder,
   object[] index,
   CultureInfo culture
);
Parameters:

obj

The object whose property value will be returned.

invokeAttr

The invocation attribute. This must be a bit flag from BindingFlags: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, or SetProperty. A suitable invocation attribute must be specified. If a static member is to be invoked, the Static flag of BindingFlags must be set.

binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects via reflection. If binder is null, the default binder is used.

index

Optional index values for indexed properties. This value should be null for non-indexed properties.

culture

The CultureInfo object that represents the culture for which the resource is to be localized. Note that if the resource is not localized for this culture, the CultureInfo.Parent method will be called successively in search of a match. If this value is null, the CultureInfo is obtained from the CultureInfo.CurrentUICulture property.

Return Value:
The property value for obj.
Exceptions
Exception Type Condition
ArgumentException The index array does not contain the type of arguments needed.

-or-

The property's Get method is not found.

TargetException The object does not match the target type, or a property is an instance property but obj is null.
TargetParameterCountException The number of parameters in index does not match the number of parameters the indexed property takes.
MethodAccessException There was an illegal attempt to access a private or protected method inside a class.
Remarks
Because static properties belong to the type, not individual objects, get static properties by passing null as the object argument. For example, use the following code to get the static CurrentCulture property of CultureInfo:

PropertyInfo CurCultProp = (typeof(CultureInfo)).GetProperty("CurrentCulture");

Console.WriteLine("CurrCult: " + CurCultProp.GetValue(null,null));

To use the GetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the GetValue method.

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumeration: ReflectionPermissionFlag.TypeInformation
See also:
Binder | BindingFlags | CultureInfo

Return to top


Method: IsDefined(
   Type attributeType,
   bool inherit
)
Inherited
See base class member description: System.Reflection.MemberInfo.IsDefined

Summary
When overridden in a derived class, indicates whether one or more instance of attributeType is defined on this member.
C# Syntax:
public abstract bool IsDefined(
   Type attributeType,
   bool inherit
);
Parameters:

attributeType

The Type object to which the custom attributes are applied.

inherit

Specifies whether to search this member's inheritance chain to find the attributes.

Return Value:
true if one or more instance of attributeType is defined on this member; otherwise false.
Implements:
ICustomAttributeProvider.IsDefined
Example

using System;
using System.Reflection;

// Define a custom attribute with one named parameter.
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
   private string myName;
   public MyAttribute(string name)
   {
      myName = name;
   }
   public string Name
   {
      get
      {
         return myName;
      }
   }
}

// Define a class which has the custom attribute associated with one of its members.
public class MyClass1
{
   [MyAttribute("This is an example attribute")]
   public void MyMethod(int i)
   {
      return;
   }
}

public class MemberInfo_GetCustomAttributes_IsDefined
{
   public static void Main()
   {
      try
      {
         // Get the type of the class 'MyClass1'.
         Type myType = typeof(MyClass1);
         // Get the members associated with the class 'MyClass1'.
         MemberInfo[] myMembers = myType.GetMembers();

         // Display the attributes for each of the members of the class 'MyClass1'.
         for(int i = 0; i < myMembers.Length; i++)
         {
            // Display the attribute if it is of type 'MyAttribute'.
            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++)
                  // Display the value associated with the attribute.
                  Console.WriteLine("The value of the attribute is : \"{0}\"",
                                       ((MyAttribute)myAttributes[j]).Name);
            }
         }
      }
      catch(Exception e)
      {
         Console.WriteLine("Exception Caught! "+e.Message);
      }
   }
}

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Overloaded Method: SetValue(
   object obj,
   object value,
   object[] index
)
Summary
Sets the value of the property with optional index values for index properties.
C# Syntax:
public virtual void SetValue(
   object obj,
   object value,
   object[] index
);
Parameters:

obj

The object whose property value will be set.

value

The new value for this property.

index

Optional index values for indexed properties. This value should be null for non-indexed properties.

Exceptions
Exception Type Condition
ArgumentException The index array does not contain the type of arguments needed.

-or-

The property's Get method is not found.

TargetException The object does not match the target type, or a property is an instance property but obj is null.
TargetParameterCountException The number of parameters in index does not match the number of parameters the indexed property takes.
MethodAccessException There was an illegal attempt to access a private or protected method inside a class.
Remarks
This is a convenience method that provides an implementation for the abstract SetValue method with a BindingFlags parameter of DefaultChangeType, the Binder set to null, and the CultureInfo set to null.

To use the SetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the SetValue method.

.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumerations: ReflectionPermissionFlag.MemberAccess, ReflectionPermissionFlag.TypeInformation

Return to top


Overloaded Method: SetValue(
   object obj,
   object value,
   BindingFlags invokeAttr,
   Binder binder,
   object[] index,
   CultureInfo culture
)
Summary
When overridden in a derived class, sets the property value for the given object to the given value.
C# Syntax:
public abstract void SetValue(
   object obj,
   object value,
   BindingFlags invokeAttr,
   Binder binder,
   object[] index,
   CultureInfo culture
);
Parameters:

obj

The object whose property value will be returned.

value

The new value for this property.

invokeAttr

The invocation attribute. This must be a bit flag from BindingFlags: InvokeMethod, CreateInstance, Static, GetField, SetField, GetProperty, or SetProperty. A suitable invocation attribute must be specified. If a static member is to be invoked, the Static flag of BindingFlags must be set.

binder

An object that enables the binding, coercion of argument types, invocation of members, and retrieval of MemberInfo objects through reflection. If binder is null, the default binder is used.

index

Optional index values for indexed properties. This value should be null for non-indexed properties.

culture

The CultureInfo object that represents the culture for which the resource is to be localized. Note that if the resource is not localized for this culture, the CultureInfo.Parent method will be called successively in search of a match. If this value is null, the CultureInfo is obtained from the CultureInfo.CurrentUICulture property.

Return Value:
An array of type MethodInfo containing the public accessors, or an empty array if there are no public accessors.
Exceptions
Exception Type Condition
ArgumentException The index array does not contain the type of arguments needed.

-or-

The property's Get method is not found.

TargetException The object does not match the target type, or a property is an instance property but obj is null.
TargetParameterCountException The number of parameters in index does not match the number of parameters the indexed property takes.
MethodAccessException There was an illegal attempt to access a private or protected method inside a class.
Remarks
Access restrictions are ignored for fully trusted code. That is, private constructors, methods, fields, and properties can be accessed and invoked via Reflection whenever the code is fully trusted.

To use the SetValue method, first get the class Type. From the Type, get the PropertyInfo. From the PropertyInfo, use the SetValue method.

Example
using System;
using System.Reflection;
 
//Make a property
 public class Myproperty   
 {
    private string caption = "A Default caption";
    public string Caption{
       get{return caption;}
       set {if(caption!=value) {caption = value;}
       }
    }
 }
 
 class Mypropertyinfo
 {
    public static int Main()
       {
       Console.WriteLine ("\nReflection.PropertyInfo");
       Myproperty Myproperty = new Myproperty();
 
       //Get the type and PropertyInfo
       Type MyType = Type.GetType("Myproperty");
       PropertyInfo Mypropertyinfo = MyType.GetProperty("Caption");
 
       //Get and display the GetValue Method
       Console.Write ("\nGetValue - "
          + Mypropertyinfo.GetValue (Myproperty, null));
 
       //Use the SetValue Method to change the caption
       Mypropertyinfo.SetValue(
          Myproperty, "This caption has been changed", null);
 
       //Get the caption again and display it
       Console.Write ("\nGetValue - "
          + Mypropertyinfo.GetValue (Myproperty, null));
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.PropertyInfo
 GetValue - A Default caption
 GetValue - This caption has been changed
 */

    
.NET Framework Security:
ReflectionPermission for reflecting non-public objects. Associated enumerations: ReflectionPermissionFlag.MemberAccess, ReflectionPermissionFlag.TypeInformation

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.