Export (0) Print
Expand All

MethodBody Class

Provides access to the metadata and MSIL for the body of a method.

System.Object
  System.Reflection.MethodBody

Namespace:  System.Reflection
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
public class MethodBody

The MethodBody type exposes the following members.

  NameDescription
Protected methodMethodBodyInitializes a new instance of the MethodBody class.
Top

  NameDescription
Public propertyExceptionHandlingClausesGets a list that includes all the exception-handling clauses in the method body.
Public propertyInitLocalsGets a value indicating whether local variables in the method body are initialized to the default values for their types.
Public propertyLocalSignatureMetadataTokenGets a metadata token for the signature that describes the local variables for the method in metadata.
Public propertyLocalVariablesGets the list of local variables declared in the method body.
Public propertyMaxStackSizeGets the maximum number of items on the operand stack when the method is executing.
Top

  NameDescription
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetILAsByteArrayReturns the MSIL for the method body, as an array of bytes.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

The MethodBody class provides access to information about the local variables and exception-handling clauses in a method body, and to the Microsoft intermediate language (MSIL) that makes up the method body.

You can use the token-resolution methods of the module class, such as ResolveType, ResolveMethod, and ResolveType, to resolve the tokens in the method body to Type objects, MethodInfo objects, and FieldInfo objects that provide detailed information about the types, methods, and fields accessed by the MSIL in the method body.

NoteNote

Parsing method bodies requires a thorough understanding of metadata and MSIL instruction formats. Information can be found in the Common Language Infrastructure (CLI) documentation, especially "Partition II: Metadata Definition and Semantics" and "Partition III: CIL Instruction Set". The documentation is available online; see ECMA C# and Common Language Infrastructure Standards on MSDN and Standard ECMA-335 - Common Language Infrastructure (CLI) on the Ecma International Web site.

To obtain a MethodBody object for a given method, first obtain a MethodInfo object for the method, then call the MethodInfo object's GetMethodBody method.

The following code example defines a test method named MethodBodyExample and displays its local variable information and exception-handling clauses. The MethodBase.GetMethodBody method is used to obtain a MethodBody object for the test method.

The example uses the LocalVariables property to obtain a list of LocalVariableInfo objects and then displays their types and index order. The ExceptionHandlingClauses property is used to obtain a list of exception-handling clauses.

NoteNote

Not all computer languages can generate ExceptionHandlingClauseOptions.Filter clauses. The Visual Basic example shows a filter clause, using a Visual Basic When expression, which is omitted from the examples for other languages.

using System;
using System.Reflection;

public class Example
{
    public static void Main()
    {
        // Get method body information.
        MethodInfo mi = typeof(Example).GetMethod("MethodBodyExample");
        MethodBody mb = mi.GetMethodBody();
        Console.WriteLine("\r\nMethod: {0}", mi);

        // Display the general information included in the  
        // MethodBody object.
        Console.WriteLine("    Local variables are initialized: {0}", 
            mb.InitLocals);
        Console.WriteLine("    Maximum number of items on the operand stack: {0}", 
            mb.MaxStackSize);

        // Display information about the local variables in the 
        // method body.
        Console.WriteLine();
        foreach (LocalVariableInfo lvi in mb.LocalVariables)
        {
            Console.WriteLine("Local variable: {0}", lvi);
        }

        // Display exception handling clauses.
        Console.WriteLine();
        foreach (ExceptionHandlingClause ehc in mb.ExceptionHandlingClauses)
        {
            Console.WriteLine(ehc.Flags.ToString());

            // The FilterOffset property is meaningful only for Filter 
            // clauses. The CatchType property is not meaningful for  
            // Filter or Finally clauses.  
            switch (ehc.Flags)
            {
                case ExceptionHandlingClauseOptions.Filter:
                    Console.WriteLine("        Filter Offset: {0}", 
                        ehc.FilterOffset);
                    break;
                case ExceptionHandlingClauseOptions.Finally:
                    break;
                default:
                    Console.WriteLine("    Type of exception: {0}", 
                        ehc.CatchType);
                    break;
            }

            Console.WriteLine("       Handler Length: {0}", ehc.HandlerLength);
            Console.WriteLine("       Handler Offset: {0}", ehc.HandlerOffset);
            Console.WriteLine("     Try Block Length: {0}", ehc.TryLength);
            Console.WriteLine("     Try Block Offset: {0}", ehc.TryOffset);
        }
    }

    // The Main method contains code to analyze this method, using 
    // the properties and methods of the MethodBody class. 
    public void MethodBodyExample(object arg)
    {
        // Define some local variables. In addition to these variables, 
        // the local variable list includes the variables scoped to  
        // the catch clauses. 
        int var1 = 42;
        string var2 = "Forty-two";

        try
        {
            // Depending on the input value, throw an ArgumentException or  
            // an ArgumentNullException to test the Catch clauses. 
            if (arg == null)
            {
                throw new ArgumentNullException("The argument cannot be null.");
            }
            if (arg.GetType() == typeof(string))
            {
                throw new ArgumentException("The argument cannot be a string.");
            }        
        }

        // There is no Filter clause in this code example. See the Visual  
        // Basic code for an example of a Filter clause. 

        // This catch clause handles the ArgumentException class, and 
        // any other class derived from Exception. 
        catch(Exception ex)
        {
            Console.WriteLine("Ordinary exception-handling clause caught: {0}", 
                ex.GetType());
        }        
        finally
        {
            var1 = 3033;
            var2 = "Another string.";
        }
    }
}

// This code example produces output similar to the following: 
// 
//Method: Void MethodBodyExample(System.Object) 
//    Local variables are initialized: True 
//    Maximum number of items on the operand stack: 2 
// 
//Local variable: System.Int32 (0) 
//Local variable: System.String (1) 
//Local variable: System.Exception (2) 
//Local variable: System.Boolean (3) 
// 
//Clause 
//    Type of exception: System.Exception 
//       Handler Length: 21 
//       Handler Offset: 70 
//     Try Block Length: 61 
//     Try Block Offset: 9 
//Finally 
//       Handler Length: 14 
//       Handler Offset: 94 
//     Try Block Length: 85 
//     Try Block Offset: 9

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft