System.Reflection.MethodBase Class

Assembly: Mscorlib.dll
Namespace: System.Reflection
Summary
Provides information about methods and constructors.
C# Syntax:
[Serializable]
public abstract class MethodBase : MemberInfo
Remarks
MethodBase is the base class of MethodInfo and ConstructorInfo.

Notes to inheritors: When you inherit from MethodBase, you must override the following members: MethodBase.GetParameters, the abstract overload of MethodBase.Invoke, and MethodBase.GetMethodImplementationFlags.
See also:
System.Reflection Namespace

System.Reflection.MethodBase Member List:

Public Properties
Attributes Read-only

Gets the attributes associated with this method.
CallingConvention Read-only

Gets a value indicating the calling conventions for this method.
DeclaringType
(inherited from System.Reflection.MemberInfo)
Read-only

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


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

Gets a value indicating whether the method is abstract.
IsAssembly Read-only

Gets a value indicating whether this method can be called by other classes in the same assembly.
IsConstructor Read-only

Gets a value indicating whether the method is a constructor.
IsFamily Read-only

Gets a value indicating whether access to this method is restricted to members of the class and members of its derived classes.
IsFamilyAndAssembly Read-only

Gets a value indicating whether this method can be called by derived classes if they are in the same assembly.
IsFamilyOrAssembly Read-only

Gets a value indicating whether this method can be called by derived classes, wherever they are, and by all classes in the same assembly.
IsFinal Read-only

Gets a value indicating whether this method is final.
IsHideBySig Read-only

Gets a value indicating whether only a member of the same kind with exactly the same signature is hidden in the derived class.
IsPrivate Read-only

Gets a value indicating whether this member is private.
IsPublic Read-only

Gets a value indicating whether this is a public method.
IsSpecialName Read-only

Gets a value indicating whether this method has a special name.
IsStatic Read-only

Gets a value indicating whether the method is static.
IsVirtual Read-only

Gets a value indicating whether the method is virtual.
MemberType
(inherited from System.Reflection.MemberInfo)
Read-only

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


Gets the type of this member, such as field, method, and so on.
MethodHandle Read-only

Gets a handle to the internal metadata representation of a method.
Name
(inherited from System.Reflection.MemberInfo)
Read-only

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


Gets the name of this member.
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.
GetCurrentMethod Returns a MethodBase object representing the currently executing method.
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.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetMethodFromHandle Gets method information by using the method's internal metadata representation (handle).
GetMethodImplementationFlags When overridden in a derived class, returns the MethodImplAttributes flags.
GetParameters When overridden in a derived class, gets the parameters of the specified method or constructor.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

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

Invokes the underlying method or constructor represented by this MethodInfo object with the specified parameters.
Invoke Overloaded:
Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)

When overridden in a derived class, invokes the reflected method or constructor with the given parameters.
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.
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 MethodBase 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.MethodBase Member Details

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

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

Return to top


Property: Attributes (read-only)
Summary
Gets the attributes associated with this method.
C# Syntax:
public abstract MethodAttributes Attributes {get;}
Remarks
All members have a set of attributes, which are defined in relation to the specific type of member.

To get the MethodAttributes, first get the type. From the type, get the method. From the method, get the MethodAttributes.



Notes to implementors: Use Attributes to determine whether a method is public, private, final, virtual, and so on.
Example

 using System;
 using System.Reflection;
 
 class AttributesSample
 {
    public void Mymethod (int int1m, out string str2m, ref string str3m)
    {
       str2m = "in Mymethod";
    }
 
    public static int Main(string[] args)
    {      
       Console.WriteLine ("Reflection.MethodBase.Attributes Sample");
       
       // Get our type
       Type MyType = Type.GetType("AttributesSample");
 
       // Get the method Mymethod on our type
       MethodBase Mymethodbase = MyType.GetMethod("Mymethod");
 
       // Print out the method
       Console.WriteLine("Mymethodbase = " + Mymethodbase);
 
       // Get the MethodAttribute enumerated value
       MethodAttributes Myattributes = Mymethodbase.Attributes;
 
       // print out the flags set
       PrintAttributes( typeof( System.Reflection.MethodAttributes ), (int) Myattributes );
       return 0;
    }
 
 
    public static void PrintAttributes( Type attribType, int iAttribValue )
    {
       if ( ! attribType.IsEnum ) { Console.WriteLine( "This type is not an enum" ); return; }
 
       FieldInfo[] fields = attribType.GetFields(BindingFlags.Public | BindingFlags.Static);
       for ( int i = 0; i < fields.Length; i++ )
       {
          int fieldvalue = (Int32)fields[i].GetValue(null);
          if ( (fieldvalue & iAttribValue) == fieldvalue )
          {
             Console.WriteLine( "\t" + fields[i].Name );
          }
       }
    }
 }
/* 
 This code produces the following output:
 
 Reflection.MethodBase.Attributes Sample
 Mymethodbase = Void Mymethod (Int32, System.String ByRef, System.String ByRef)
         PrivateScope
         FamANDAssem
         Family
         Public 
         HideBySig 
         ReuseSlot
*/

    
See also:
MethodAttributes

Return to top


Property: CallingConvention (read-only)
Summary
Gets a value indicating the calling conventions for this method.
C# Syntax:
public virtual CallingConventions CallingConvention {get;}
See also:
CallingConventions

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: IsAbstract (read-only)
Summary
Gets a value indicating whether the method is abstract.
C# Syntax:
public bool IsAbstract {get;}
Remarks
An abstract member is declared on a base class and has no implementation supplied.

To get the MethodBase, first get the type. From the type, get the method. From the method, get the MethodBase. If the MethodBase or constructor is other than public, it is protected and cannot be readily accessed. To access a non-public method, set the BindingFlags mask to NonPublic in GetMethod.

Example
 class methodbase
 {
    public static int Main(string[] args)
    {      
       Console.WriteLine ("\nReflection.MethodBase");
       
       //Get the MethodBase of two methods.
 
       //Get the types
       Type MyType1 = Type.GetType("System.Runtime.Serialization.Formatter");       
       Type MyType2 = Type.GetType("System.Reflection.MethodBase");
 
       //Get and display the methods
       MethodBase Mymethodbase1 = 
          MyType1.GetMethod("WriteInt32", BindingFlags.NonPublic|BindingFlags.Instance);

       MethodBase Mymethodbase2 = 
          MyType2.GetMethod("GetCurrentMethod", BindingFlags.Public|BindingFlags.Static);
 
       Console.Write("\nMymethodbase = " + Mymethodbase1.ToString());
       if (Mymethodbase1.IsAbstract)
          Console.Write ("\nMymethodbase is an abstract method");
       else
          Console.Write ("\nMymethodbase is not an abstract method");
 
       Console.Write("\n\nMymethodbase = " + Mymethodbase2.ToString());
       if (Mymethodbase2.IsAbstract)
          Console.Write ("\nMymethodbase is an abstract method");
       else
          Console.Write ("\nMymethodbase is not an abstract method");
       
       return 0;
    }
 }
 /*
 Produces the following output
 Reflection.MethodBase
 
 Mymethodbase = Void WriteInt32 (Int32, System.String)
 Mymethodbase is an abstract method
 
 Mymethodbase = System.Reflection.MethodBase GetCurrentMethod ()
 Mymethodbase is not an abstract method
 */

    
See also:
Boolean | BindingFlags

Return to top


Property: IsAssembly (read-only)
Summary
Gets a value indicating whether this method can be called by other classes in the same assembly.
C# Syntax:
public bool IsAssembly {get;}
Remarks
If set, this method can be called by other classes in the same assembly.

To get the MethodBase, first get the type. From the type, get the method. From the method, get the MethodBase. If the MethodBase or constructor is other than public, it is protected and cannot be readily accessed. To access a non-public method, set the BindingFlags mask to NonPublic in GetMethod.

Example
 class methodbase
 {
	internal void f() { }
    public static int Main(string[] args)
    { 
       Console.WriteLine ("\nReflection.MethodBase");
       
       //Get the MethodBase of two methods.
 
       //Get the types
       Type MyType1 = Type.GetType("System.Runtime.Serialization.Formatter");
       Type MyType2 = Type.GetType("methodbase");
 
       //Get and display the methods and the IsAssembly
       MethodBase Mymethodbase1 = 
          MyType1.GetMethod("WriteInt32",BindingFlags.NonPublic|BindingFlags.Instance);
       MethodBase Mymethodbase2 = 
          MyType2.GetMethod("f", BindingFlags.NonPublic|BindingFlags.Instance);
 
       Console.Write("\nMymethodbase = " + Mymethodbase1.ToString());
       if (Mymethodbase1.IsAssembly)
          Console.Write ("\nMymethodbase is an assembly method");
       else
          Console.Write ("\nMymethodbase is not an assembly method");
 
       Console.Write("\n\nMymethodbase = " + Mymethodbase2.ToString());
       if (Mymethodbase2.IsAssembly)
          Console.Write ("\nMymethodbase is an assembly method");
       else
          Console.Write ("\nMymethodbase is not an assembly method");
       
       return 0;
    }
 }
 /*
 Produces the following output
 Reflection.MethodBase
 
 Mymethodbase = Void WriteInt32 (Int32, System.String)
 Mymethodbase is not an assembly method
 
 Mymethodbase = Void f()
 Mymethodbase is an assembly method
 */

    
See also:
FieldAttributes | Boolean | BindingFlags

Return to top


Property: IsConstructor (read-only)
Summary
Gets a value indicating whether the method is a constructor.
C# Syntax:
public bool IsConstructor {get;}
See also:
Boolean

Return to top


Property: IsFamily (read-only)
Summary
Gets a value indicating whether access to this method is restricted to members of the class and members of its derived classes.
C# Syntax:
public bool IsFamily {get;}
Remarks
If a type member has Family level visibility it can be called from any member in a derived class, but not from any other type.
See also:
Boolean

Return to top


Property: IsFamilyAndAssembly (read-only)
Summary
Gets a value indicating whether this method can be called by derived classes if they are in the same assembly.
C# Syntax:
public bool IsFamilyAndAssembly {get;}
See also:
Boolean

Return to top


Property: IsFamilyOrAssembly (read-only)
Summary
Gets a value indicating whether this method can be called by derived classes, wherever they are, and by all classes in the same assembly.
C# Syntax:
public bool IsFamilyOrAssembly {get;}
Remarks
If a type member has FamilyOrAssembly level visibility it can be called from any member in a derived class or any member in the same assembly, but not from any other type.
See also:
Boolean

Return to top


Property: IsFinal (read-only)
Summary
Gets a value indicating whether this method is final.
C# Syntax:
public bool IsFinal {get;}
Remarks
To determine if a method is overridable, it is not sufficient to check that MethodBase.IsVirtual is true. For a method to be overridable, IsVirtual must be true and IsFinal must be false. For example, a method might be non-virtual, but it implements an interface method. The common language runtime requires that all methods that implement interface members must be marked as virtual; therefore, the compiler marks the method virtualfinal. So there are cases where a method is marked as virtual but is still not overridable.

To establish with certainty whether a method is overridable, use code such as this:

if (MethodInfo.IsVirtual && !MethodInfo.IsFinal)

If IsVirtual is false or IsFinal is true, then the method cannot be overridden.

Example
This example prints false for IsFinal, which might lead you to think that MyMethod is overridable. The code prints false even though MyMethod is not marked virtual and thus cannot be overridden.
 using System;
 using System.Reflection;
 
 public class MyClass 
 {
 public void MyMethod() 
   {
   }
 public static void Main() 
   {
    MethodBase m = typeof(MyClass).GetMethod("MyMethod");
    Console.WriteLine(m.IsFinal);
   }
 }

    
See also:
Boolean

Return to top


Property: IsHideBySig (read-only)
Summary
Gets a value indicating whether only a member of the same kind with exactly the same signature is hidden in the derived class.
C# Syntax:
public bool IsHideBySig {get;}

Return to top


Property: IsPrivate (read-only)
Summary
Gets a value indicating whether this member is private.
C# Syntax:
public bool IsPrivate {get;}
Remarks
If a type member has Private level visibility, it can be called from any member in the same class and no others.
See also:
Boolean

Return to top


Property: IsPublic (read-only)
Summary
Gets a value indicating whether this is a public method.
C# Syntax:
public bool IsPublic {get;}
Remarks
To get the MethodBase, first get the type. From the type, get the method. From the method, get the MethodBase. If the MethodBase or constructor is other than public, it is protected and cannot be readily accessed. To access a non-public method, set the BindingFlags mask to NonPublic in GetMethod.
Example
 class methodbase
 {
    public static int Main(string[] args)
    {     
 
       Console.WriteLine("\nReflection.MethodBase");
       
       //Get the MethodBase of a method.
  
       //Get the type
       Type MyType = Type.GetType("System.MulticastDelegate");
  
       //Get and display the method
       MethodBase Mymethodbase =
          MyType.GetMethod("RemoveImpl",BindingFlags.NonPublic);
  
       Console.Write("\nMymethodbase = " + Mymethodbase);
  
       bool Myispublic = Mymethodbase.IsPublic;
       if (Myispublic)
          Console.Write ("\nMymethodbase is a public method");
       else
          Console.Write ("\nMymethodbase is not a public method");
       
       return 0;
    }
 }
 /*
 Produces the following output
 
 Reflection.MethodBase
 Mymethodbase = System.Delegate RemoveImpl (System.Delegate)
 Mymethodbase is not a public method
 */

    
See also:
Boolean | BindingFlags

Return to top


Property: IsSpecialName (read-only)
Summary
Gets a value indicating whether this method has a special name.
C# Syntax:
public bool IsSpecialName {get;}
Remarks
The MethodAttributes.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).
See also:
Boolean | MethodAttributes

Return to top


Property: IsStatic (read-only)
Summary
Gets a value indicating whether the method is static.
C# Syntax:
public bool IsStatic {get;}
Remarks
A static member cannot implicitly reference instance data in a class (see MethodAttributes.Static).
See also:
Boolean | MethodAttributes

Return to top


Property: IsVirtual (read-only)
Summary
Gets a value indicating whether the method is virtual.
C# Syntax:
public bool IsVirtual {get;}
Remarks
A virtual member may reference instance data in a class and must be referenced through an instance of the class.

To determine if a method is overridable, it is not sufficient to check that IsVirtual is true. For a method to be overridable, IsVirtual must be true and MethodBase.IsFinal must be false. For example, a method might be non-virtual, but it implements an interface method. The common language runtime requires that all methods that implement interface members must be marked as virtual; therefore, the compiler marks the method virtualfinal. So there are cases where a method is marked as virtual but is still not overridable.

To establish with certainty whether a method is overridable, use code such as this:

if (MethodInfo.IsVirtual && !MethodInfo.IsFinal)

If IsVirtual is false or IsFinal is true, then the method cannot be overridden.

Example
This example prints false for IsFinal, which might lead you to think that MyMethod is overridable. The code prints false even though MyMethod is not marked virtual and thus cannot be overridden.
 using System;
 using System.Reflection;
 
 public class MyClass 
 {
 public void MyMethod() 
   {
   }
 public static void Main() 
   {
    MethodBase m = typeof(MyClass).GetMethod("MyMethod");
    Console.WriteLine(m.IsFinal);
   }
 }

    

Return to top


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

Summary
Gets the type of this member, such as field, method, and so on.
C# Syntax:
public abstract MemberTypes MemberType {get;}
Remarks
To get the MemberType property, get the class Type. From the Type, get the MethodInfo array. From the MethodInfo array, get the MemberTypes.
Example
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.Reflection.PropertyInfo");
       MemberInfo[] Mymemberinfoarray = MyType.GetMembers();
  
       //Get the MemberType method and display the elements.
       Console.Write("\nThere are {0} members in ",
          Mymemberinfoarray.GetLength(0));
       Console.Write("{0}.", MyType.FullName);
  
       for (int counter = 0; counter < Mymemberinfoarray.Length; counter++)
       {
          Console.Write("\n" + counter + ". " 
             + Mymemberinfoarray[counter].Name
             + " Member type - " +
             Mymemberinfoarray[counter].MemberType.ToString());
       }
       return 0;
    }
 }
 /*
 This code produces the following output:
 Reflection.MemberInfo
  
 There are 52 members in System.Reflection.PropertyInfo.
 37. GetCanRead Member type - Method
 38. GetCanWrite Member type - Method
 39. MemberType Member type - Property
 40. PropertyType Member type - Property
 */

    
See also:
MemberTypes

Return to top


Property: MethodHandle (read-only)
Summary
Gets a handle to the internal metadata representation of a method.
C# Syntax:
public abstract RuntimeMethodHandle MethodHandle {get;}
Remarks
The handles are valid only in the application domain in which they were obtained.

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: 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:
~MethodBase();

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

Return to top


Method: GetCurrentMethod()
Summary
Returns a MethodBase object representing the currently executing method.
C# Syntax:
public static MethodBase GetCurrentMethod();
Return Value:
A MethodBase object representing the currently executing method.

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


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: GetMethodFromHandle(
   RuntimeMethodHandle handle
)
Summary
Gets method information by using the method's internal metadata representation (handle).
C# Syntax:
public static MethodBase GetMethodFromHandle(
   RuntimeMethodHandle handle
);
Parameters:

handle

The method's handle.

Return Value:
MethodBase information about the method.
Remarks
The handles are valid only in the application domain in which they were obtained.

Return to top


Method: GetMethodImplementationFlags()
Summary
When overridden in a derived class, returns the MethodImplAttributes flags.
C# Syntax:
public abstract MethodImplAttributes GetMethodImplementationFlags();
Return Value:
The MethodImplAttributes flags.
See also:
MethodImplAttributes

Return to top


Method: GetParameters()
Summary
When overridden in a derived class, gets the parameters of the specified method or constructor.
C# Syntax:
public abstract ParameterInfo[] GetParameters();
Return Value:
An array of type ParameterInfo containing information that matches the signature of the method (or constructor) reflected by this MethodBase instance.
See also:
ParameterInfo

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: Invoke(
   object obj,
   object[] parameters
)
Summary
Invokes the underlying method or constructor represented by this MethodInfo object with the specified parameters.
C# Syntax:
public object Invoke(
   object obj,
   object[] parameters
);
Parameters:

obj

The instance that created this method.

parameters

An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, this should be null.

If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. If the parameters contain an uninitialized object, it is treated as System.Empty, which, with the default binder, can be widened to 0, 0.0 or String.

An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, this should be null.

If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. If the parameters contain an uninitialized object, it is treated as System.Empty, which, with the default binder, can be widened to 0, 0.0 or String.

Return Value:
An Object containing the return value of the invoked method, or a re-initialized object in the case of a constructor.
Exceptions
Exception Type Condition
TargetException The obj parameter is null and the method is not static.

-or-

The method is not declared or inherited by the class of obj.

ArgumentException The type of the parameters parameter does not match the signature of the method or constructor reflected by this instance.
MemberAccessException The caller does not have permission to invoke the method or constructor.
TargetInvocationException The invoked method or constructor throws an exception.
TargetParameterCountException The parameters array does not have the correct number of arguments.
MethodAccessException The caller does not have permission to execute the constructor.
Remarks
Use this method to invoke methods with parameters that have default values. To bind to these methods, Reflection requires one of the binding flags DefaultValueBinding, DefaultValueChangeType, or DefaultValueFull to be specified explicitly. This is a requirement even in those cases where a value is passed for a parameter that has a default value.

For example, consider a method such as MyMethod(int x, float y = 2.0). To invoke this method with only the first argument as MyMethod(4), pass one of the above binding flags and pass two arguments, namely, 4 for the first argument and Missing.Value for the second argument. Unless you use Missing.Value, you may not omit optional parameters with the Invoke method. If you must do so, use Type.InvokeMember instead.

This is a convenience method that calls the following Invoke method, passing null in the other parameters. If the invoked method throws an exception, Exception.GetBaseException returns the exception.

To invoke a static method using its MethodInfo object, the first parameter should be null, as shown in the following call:

Object myReturnValue = myMethodInfo.Invoke(null, myParametersArray);

See also:
BindingFlags | Missing

Return to top


Overloaded Method: Invoke(
   object obj,
   BindingFlags invokeAttr,
   Binder binder,
   object[] parameters,
   CultureInfo culture
)
Summary
When overridden in a derived class, invokes the reflected method or constructor with the given parameters.
C# Syntax:
public abstract object Invoke(
   object obj,
   BindingFlags invokeAttr,
   Binder binder,
   object[] parameters,
   CultureInfo culture
);
Parameters:

obj

The object on which to invoke the method or constructor. If the method or constructor is static, this argument is ignored.

invokeAttr

A bitmask that is a combination of 0 or more bit flags from BindingFlags, such as DefaultBinding, NonPublic, and so on. If binder is null, this parameter will be assigned the value BindingFlags.DefaultBinding; thus, whatever you pass in is ignored.

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.

parameters

An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, this should be null.

If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. If the parameters contain an uninitialized object, it is treated as System.Empty, which, with the default binder, can be widened to 0, 0.0 or String.

An argument list for the invoked method or constructor. This is an array of objects with the same number, order, and type as the parameters of the method or constructor to be invoked. If there are no parameters, this should be null.

If the method or constructor represented by this instance takes a ByRef parameter, there is no special attribute required for that parameter in order to invoke the method or constructor using this function. If the parameters contain an uninitialized object, it is treated as System.Empty, which, with the default binder, can be widened to 0, 0.0 or String.

culture

An instance of CultureInfo used to govern the coercion of types. If this is null, the CultureInfo for the current thread is used. (This is necessary to convert a String that represents 1000 to a Double value, for example, since 1000 is represented differently by different cultures.)

Return Value:
An Object containing the return value of the invoked method, or a reinitialized object in the case of a constructor, or null if the method's return type is void. Before calling the method or constructor, Invoke checks to see if the user has access permission and verify that the parameters are valid.
Exceptions
Exception Type Condition
TargetException The obj parameter is null and the method is not static. -or-

The method is not declared or inherited by the class of obj.

ArgumentException The type of the parameters parameter does not match the signature of the method or constructor reflected by this instance.
MemberAccessException The caller does not have permission to invoke the method or constructor.
TargetInvocationException The invoked method or constructor throws an exception.
MethodAccessException The caller does not have permission to execute the constructor.
Remarks
Dynamically invokes the method reflected by this instance on obj, and passes along the specified parameters. If the method is static, the obj parameter is ignored. For non-static methods, obj should be an instance of a class that inherits or declares the method and must be the same type as this class. If the method has no parameters, the value of parameters should be null. Otherwise, the number, type, and order of elements in parameters should be identical to the number, type, and order of parameters for the method reflected by this instance.

You may not omit optional parameters in calls to Invoke. To invoke a method omitting optional parameters, you should call Type.InvokeMember instead.

For pass-by-value primitive parameters, normal widening is performed (Int16 -> Int32, for example). For pass-by-value reference parameters, normal reference widening is allowed (derived class to base class, and base class to interface type). However, for pass-by-reference primitive parameters, the types must match exactly. For pass-by-reference reference parameters, the normal widening still applies.

For example, if the method reflected by this instance is declared as public boolean Compare(String a, String b) , then parameters should be an array of Objects with length 2 such that parameters[0] = new Object("SomeString1") and parameters[1] = new Object("SomeString2") .

Reflection uses dynamic method lookup when invoking virtual methods. For example, suppose that class B inherits from class A and both implement a virtual method named M. Now suppose that you have a MethodInfo object that represents M on class A. If you use the Invoke method to invoke M on an object of type B, then reflection will use the implementation given by class B. Even if the object of type B is cast to A, the implementation given by class B is used (see code sample below).

On the other hand, if the method is non-virtual, then reflection will use the implementation given by the type from which the MethodInfo was obtained, regardless of the type of the object passed as the target.

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.

If the invoked method throws an exception, TargetInvocationException.GetException returns the exception. This implementation throws a NotSupportedException.

Example
The following samples in C++ and C# demonstrate dynamic method lookup using reflection. Note that all of the invocations return 1, because the method in classes A and B is virtual.
 public class A
 {
    public virtual int method () {return 0;}
 }
 
 public class B
 {
    public virtual int method () {return 1;}
 }
 
 class Mymethodinfo
 {
    public static int Main()
    {
       Console.WriteLine ("\nReflection.MethodInfo");
       A MyA = new A();
       B MyB = new B();
 
       //Get the Type and MethodInfo
       Type MyTypea = Type.GetType("A");
       MethodInfo Mymethodinfoa = MyTypea.GetMethod("method");
 
       Type MyTypeb = Type.GetType("B");
       MethodInfo Mymethodinfob = MyTypeb.GetMethod("method");
 
       //Get and display the Invoke method
       Console.Write("\nFirst method - " + MyTypea.FullName +
          " returns " + Mymethodinfoa.Invoke(MyA, null));
       Console.Write("\nSecond method - " + MyTypeb.FullName +
          " returns " + Mymethodinfob.Invoke(MyB, null));
 
       return 0;
    }
 }

    

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


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.