System.Reflection.Emit.MethodBuilder class
This article provides supplementary remarks to the reference documentation for this API.
The MethodBuilder class is used to fully describe a method in common intermediate language (CIL), including the name, attributes, signature, and method body. It is used in conjunction with the TypeBuilder class to create classes at runtime.
You can use reflection emit to define global methods and to define methods as type members. The APIs that define methods return MethodBuilder objects.
Global methods
A global method is defined by using the ModuleBuilder.DefineGlobalMethod method, which returns a MethodBuilder
object.
Global methods must be static. If a dynamic module contains global methods, the ModuleBuilder.CreateGlobalFunctions method must be called before persisting the dynamic module or the containing dynamic assembly because the common language runtime postpones fixing up the dynamic module until all global functions have been defined.
A global native method is defined by using the ModuleBuilder.DefinePInvokeMethod method. Platform invoke (PInvoke) methods must not be declared abstract or virtual. The runtime sets the MethodAttributes.PinvokeImpl attribute for a platform invoke method.
Methods as members of types
A method is defined as a type member by using the TypeBuilder.DefineMethod method, which returns a MethodBuilder object.
The DefineParameter method is used to set the name and parameter attributes of a parameter, or of the return value. The ParameterBuilder object returned by this method represents a parameter or the return value. The ParameterBuilder object can be used to set the marshaling, to set the constant value, and to apply custom attributes.
Attributes
Members of the MethodAttributes enumeration define the precise character of a dynamic method:
- Static methods are specified using the MethodAttributes.Static attribute.
- Final methods (methods that cannot be overridden) are specified using the MethodAttributes.Final attribute.
- Virtual methods are specified using the MethodAttributes.Virtual attribute.
- Abstract methods are specified using the MethodAttributes.Abstract attribute.
- Several attributes determine method visibility. See the description of the MethodAttributes enumeration.
- Methods that implement overloaded operators must set the MethodAttributes.SpecialName attribute.
- Finalizers must set the MethodAttributes.SpecialName attribute.
Known issues
- Although MethodBuilder is derived from MethodInfo, some of the abstract methods defined in the MethodInfo class are not fully implemented in MethodBuilder. These MethodBuilder methods throw the NotSupportedException. For example the MethodBuilder.Invoke method is not fully implemented. You can reflect on these methods by retrieving the enclosing type using the Type.GetType or Assembly.GetType methods.
- Custom modifiers are supported.