AssemblyBuilder Class

 

Defines and represents a dynamic assembly.

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

System.Object
  System.Reflection.Assembly
    System.Reflection.Emit.AssemblyBuilder

[ClassInterfaceAttribute(ClassInterfaceType.None)]
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
public sealed class AssemblyBuilder : Assembly, _AssemblyBuilder

NameDescription
System_CAPS_pubpropertyCodeBase

Gets the location of the assembly, as specified originally (such as in an AssemblyName object).(Overrides Assembly.CodeBase.)

System_CAPS_pubpropertyCustomAttributes

Gets a collection that contains this assembly's custom attributes.(Inherited from Assembly.)

System_CAPS_pubpropertyDefinedTypes

Gets a collection of the types defined in this assembly.(Inherited from Assembly.)

System_CAPS_pubpropertyEntryPoint

Returns the entry point of this assembly.(Overrides Assembly.EntryPoint.)

System_CAPS_pubpropertyEscapedCodeBase

Gets the URI, including escape characters, that represents the codebase.(Inherited from Assembly.)

System_CAPS_pubpropertyEvidence

Gets the evidence for this assembly.(Overrides Assembly.Evidence.)

System_CAPS_pubpropertyExportedTypes

Gets a collection of the public types defined in this assembly that are visible outside the assembly.(Inherited from Assembly.)

System_CAPS_pubpropertyFullName

Gets the display name of the current dynamic assembly. (Overrides Assembly.FullName.)

System_CAPS_pubpropertyGlobalAssemblyCache

Gets a value that indicates whether the assembly was loaded from the global assembly cache.(Overrides Assembly.GlobalAssemblyCache.)

System_CAPS_pubpropertyHostContext

Gets the host context where the dynamic assembly is being created.(Overrides Assembly.HostContext.)

System_CAPS_pubpropertyImageRuntimeVersion

Gets the version of the common language runtime that will be saved in the file containing the manifest.(Overrides Assembly.ImageRuntimeVersion.)

System_CAPS_pubpropertyIsDynamic

Gets a value that indicates that the current assembly is a dynamic assembly.(Overrides Assembly.IsDynamic.)

System_CAPS_pubpropertyIsFullyTrusted

Gets a value that indicates whether the current assembly is loaded with full trust.(Inherited from Assembly.)

System_CAPS_pubpropertyLocation

Gets the location, in codebase format, of the loaded file that contains the manifest if it is not shadow-copied.(Overrides Assembly.Location.)

System_CAPS_pubpropertyManifestModule

Gets the module in the current AssemblyBuilder that contains the assembly manifest.(Overrides Assembly.ManifestModule.)

System_CAPS_pubpropertyModules

Gets a collection that contains the modules in this assembly.(Inherited from Assembly.)

System_CAPS_pubpropertyPermissionSet

Gets the grant set of the current dynamic assembly.(Overrides Assembly.PermissionSet.)

System_CAPS_pubpropertyReflectionOnly

Gets a value indicating whether the dynamic assembly is in the reflection-only context.(Overrides Assembly.ReflectionOnly.)

System_CAPS_pubpropertySecurityRuleSet

Gets a value that indicates which set of security rules the common language runtime (CLR) enforces for this assembly.(Overrides Assembly.SecurityRuleSet.)

NameDescription
System_CAPS_pubmethodAddResourceFile(String, String)

Adds an existing resource file to this assembly.

System_CAPS_pubmethodAddResourceFile(String, String, ResourceAttributes)

Adds an existing resource file to this assembly.

System_CAPS_pubmethodCreateInstance(String)

Locates the specified type from this assembly and creates an instance of it using the system activator, using case-sensitive search.(Inherited from Assembly.)

System_CAPS_pubmethodCreateInstance(String, Boolean)

Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search.(Inherited from Assembly.)

System_CAPS_pubmethodCreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Locates the specified type from this assembly and creates an instance of it using the system activator, with optional case-sensitive search and having the specified culture, arguments, and binding and activation attributes.(Inherited from Assembly.)

System_CAPS_pubmethodSystem_CAPS_staticDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess)

Defines a dynamic assembly that has the specified name and access rights.

System_CAPS_pubmethodSystem_CAPS_staticDefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess, IEnumerable<CustomAttributeBuilder>)

Defines a new assembly that has the specified name, access rights, and attributes.

System_CAPS_pubmethodDefineDynamicModule(String)

Defines a named transient dynamic module in this assembly.

System_CAPS_pubmethodDefineDynamicModule(String, Boolean)

Defines a named transient dynamic module in this assembly and specifies whether symbol information should be emitted.

System_CAPS_pubmethodDefineDynamicModule(String, String)

Defines a persistable dynamic module with the given name that will be saved to the specified file. No symbol information is emitted.

System_CAPS_pubmethodDefineDynamicModule(String, String, Boolean)

Defines a persistable dynamic module, specifying the module name, the name of the file to which the module will be saved, and whether symbol information should be emitted using the default symbol writer.

System_CAPS_pubmethodDefineResource(String, String, String)

Defines a standalone managed resource for this assembly with the default public resource attribute.

System_CAPS_pubmethodDefineResource(String, String, String, ResourceAttributes)

Defines a standalone managed resource for this assembly. Attributes can be specified for the managed resource.

System_CAPS_pubmethodDefineUnmanagedResource(Byte[])

Defines an unmanaged resource for this assembly as an opaque blob of bytes.

System_CAPS_pubmethodDefineUnmanagedResource(String)

Defines an unmanaged resource file for this assembly given the name of the resource file.

System_CAPS_pubmethodDefineVersionInfoResource()

Defines an unmanaged version information resource using the information specified in the assembly's AssemblyName object and the assembly's custom attributes.

System_CAPS_pubmethodDefineVersionInfoResource(String, String, String, String, String)

Defines an unmanaged version information resource for this assembly with the given specifications.

System_CAPS_pubmethodEquals(Object)

Returns a value that indicates whether this instance is equal to the specified object.(Overrides Assembly.Equals(Object).)

System_CAPS_pubmethodGetCustomAttributes(Boolean)

Returns all the custom attributes that have been applied to the current AssemblyBuilder.(Overrides Assembly.GetCustomAttributes(Boolean).)

System_CAPS_pubmethodGetCustomAttributes(Type, Boolean)

Returns all the custom attributes that have been applied to the current AssemblyBuilder, and that derive from a specified attribute type.(Overrides Assembly.GetCustomAttributes(Type, Boolean).)

System_CAPS_pubmethodGetCustomAttributesData()

Returns CustomAttributeData objects that contain information about the attributes that have been applied to the current AssemblyBuilder.(Overrides Assembly.GetCustomAttributesData().)

System_CAPS_pubmethodGetDynamicModule(String)

Returns the dynamic module with the specified name.

System_CAPS_pubmethodGetExportedTypes()

Gets the exported types defined in this assembly.(Overrides Assembly.GetExportedTypes().)

System_CAPS_pubmethodGetFile(String)

Gets a FileStream for the specified file in the file table of the manifest of this assembly.(Overrides Assembly.GetFile(String).)

System_CAPS_pubmethodGetFiles()

Gets the files in the file table of an assembly manifest.(Inherited from Assembly.)

System_CAPS_pubmethodGetFiles(Boolean)

Gets the files in the file table of an assembly manifest, specifying whether to include resource modules.(Overrides Assembly.GetFiles(Boolean).)

System_CAPS_pubmethodGetHashCode()

Returns the hash code for this instance.(Overrides Assembly.GetHashCode().)

System_CAPS_pubmethodGetLoadedModules()

Gets all the loaded modules that are part of this assembly.(Inherited from Assembly.)

System_CAPS_pubmethodGetLoadedModules(Boolean)

Returns all the loaded modules that are part of this assembly, and optionally includes resource modules.(Overrides Assembly.GetLoadedModules(Boolean).)

System_CAPS_pubmethodGetManifestResourceInfo(String)

Returns information about how the given resource has been persisted.(Overrides Assembly.GetManifestResourceInfo(String).)

System_CAPS_pubmethodGetManifestResourceNames()

Loads the specified manifest resource from this assembly.(Overrides Assembly.GetManifestResourceNames().)

System_CAPS_pubmethodGetManifestResourceStream(String)

Loads the specified manifest resource from this assembly.(Overrides Assembly.GetManifestResourceStream(String).)

System_CAPS_pubmethodGetManifestResourceStream(Type, String)

Loads the specified manifest resource, scoped by the namespace of the specified type, from this assembly.(Overrides Assembly.GetManifestResourceStream(Type, String).)

System_CAPS_pubmethodGetModule(String)

Gets the specified module in this assembly.(Overrides Assembly.GetModule(String).)

System_CAPS_pubmethodGetModules()

Gets all the modules that are part of this assembly.(Inherited from Assembly.)

System_CAPS_pubmethodGetModules(Boolean)

Gets all the modules that are part of this assembly, and optionally includes resource modules.(Overrides Assembly.GetModules(Boolean).)

System_CAPS_pubmethodGetName()

Gets an AssemblyName for this assembly.(Inherited from Assembly.)

System_CAPS_pubmethodGetName(Boolean)

Gets the AssemblyName that was specified when the current dynamic assembly was created, and sets the code base as specified.(Overrides Assembly.GetName(Boolean).)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

Gets serialization information with all of the data needed to reinstantiate this assembly.(Inherited from Assembly.)

System_CAPS_pubmethodGetReferencedAssemblies()

Gets an incomplete list of AssemblyName objects for the assemblies that are referenced by this AssemblyBuilder. (Overrides Assembly.GetReferencedAssemblies().)

System_CAPS_pubmethodGetSatelliteAssembly(CultureInfo)

Gets the satellite assembly for the specified culture.(Overrides Assembly.GetSatelliteAssembly(CultureInfo).)

System_CAPS_pubmethodGetSatelliteAssembly(CultureInfo, Version)

Gets the specified version of the satellite assembly for the specified culture.(Overrides Assembly.GetSatelliteAssembly(CultureInfo, Version).)

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethodGetType(String)

Gets the Type object with the specified name in the assembly instance.(Inherited from Assembly.)

System_CAPS_pubmethodGetType(String, Boolean)

Gets the Type object with the specified name in the assembly instance and optionally throws an exception if the type is not found.(Inherited from Assembly.)

System_CAPS_pubmethodGetType(String, Boolean, Boolean)

Gets the specified type from the types that have been defined and created in the current AssemblyBuilder.(Overrides Assembly.GetType(String, Boolean, Boolean).)

System_CAPS_pubmethodGetTypes()

Gets the types defined in this assembly.(Inherited from Assembly.)

System_CAPS_pubmethodIsDefined(Type, Boolean)

Returns a value that indicates whether one or more instances of the specified attribute type is applied to this member.(Overrides Assembly.IsDefined(Type, Boolean).)

System_CAPS_pubmethodLoadModule(String, Byte[])

Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file.(Inherited from Assembly.)

System_CAPS_pubmethodLoadModule(String, Byte[], Byte[])

Loads the module, internal to this assembly, with a common object file format (COFF)-based image containing an emitted module, or a resource file. The raw bytes representing the symbols for the module are also loaded.(Inherited from Assembly.)

System_CAPS_pubmethodSave(String)

Saves this dynamic assembly to disk.

System_CAPS_pubmethodSave(String, PortableExecutableKinds, ImageFileMachine)

Saves this dynamic assembly to disk, specifying the nature of code in the assembly's executables and the target platform.

System_CAPS_pubmethodSetCustomAttribute(ConstructorInfo, Byte[])

Set a custom attribute on this assembly using a specified custom attribute blob.

System_CAPS_pubmethodSetCustomAttribute(CustomAttributeBuilder)

Set a custom attribute on this assembly using a custom attribute builder.

System_CAPS_pubmethodSetEntryPoint(MethodInfo)

Sets the entry point for this dynamic assembly, assuming that a console application is being built.

System_CAPS_pubmethodSetEntryPoint(MethodInfo, PEFileKinds)

Sets the entry point for this assembly and defines the type of the portable executable (PE file) being built.

System_CAPS_pubmethodToString()

Returns the full name of the assembly, also known as the display name.(Inherited from Assembly.)

NameDescription
System_CAPS_pubeventModuleResolve

Occurs when the common language runtime class loader cannot resolve a reference to an internal module of an assembly through normal means.(Inherited from Assembly.)

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethod_Assembly.GetType()

Returns the type of the current instance.(Inherited from Assembly.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_AssemblyBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.

System_CAPS_pubinterfaceSystem_CAPS_privmethod_AssemblyBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can then be used to get the type information for an interface.

System_CAPS_pubinterfaceSystem_CAPS_privmethod_AssemblyBuilder.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

System_CAPS_pubinterfaceSystem_CAPS_privmethod_AssemblyBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.

NameDescription
System_CAPS_pubmethodGetCustomAttribute(Type)

Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified assembly.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttribute<T>()

Overloaded. Retrieves a custom attribute of a specified type that is applied to a specified assembly.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttributes()

Overloaded. Retrieves a collection of custom attributes that are applied to a specified assembly.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodGetCustomAttributes(Type)

Overloaded. Retrieves a collection of custom attributes of a specified type that are applied to a specified assembly.(Defined by CustomAttributeExtensions.)

System_CAPS_pubmethodIsDefined(Type)

Overloaded. Indicates whether custom attributes of a specified type are applied to a specified assembly.(Defined by CustomAttributeExtensions.)

A dynamic assembly is an assembly that is created using the Reflection Emit APIs. The dynamic modules in the assembly are saved when the dynamic assembly is saved using the Save method. To generate an executable, the SetEntryPoint method must be called to identify the method that is the entry point to the assembly. Assemblies are saved as DLLs by default, unless the SetEntryPoint method requests the generation of a console application or a Windows-based application.

If a dynamic assembly contains more than one dynamic module, the assembly's manifest file name should match the module's name that is specified as the first argument to the DefineDynamicModule method.

Some methods on the base Assembly class, such as GetModules and GetLoadedModules, will not work correctly when called from AssemblyBuilder objects. You can load the defined dynamic assembly and call the methods on the loaded assembly. For example, to ensure that resource modules are included in the returned module list, call GetModules on the loaded Assembly object.

The signing of a dynamic assembly using KeyPair is not effective until the assembly is saved to disk. So, strong names will not work with transient dynamic assemblies.

To get an AssemblyBuilder object, use the AppDomain.DefineDynamicAssembly method.

The following are some things to consider when using the AssemblyBuilder class to create dynamic assemblies.

Reflection emit supports the creation of dynamic modules defined in dynamic assemblies. A dynamic module created in a dynamic assembly can be transient or persistable.

Assemblies can reference types defined in another assembly. A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. This is because when the persisted dynamic module is loaded after being saved to disk, the runtime cannot resolve the references to types defined in the transient dynamic module.

Some scenarios require a dynamic assembly to be created and executed in a remote application domain. Reflection emit does not allow a dynamic assembly to be emitted directly to a remote application domain. The solution is to emit the dynamic assembly in the current application domain, save the emitted dynamic assembly to disk, and then load the dynamic assembly into the remote application domain.

Dynamic assemblies can be created using one of the following access modes:

  • AssemblyBuilderAccess.Run

    The dynamic assembly represented by an AssemblyBuilder object is transient. The dynamic assembly can only be used to execute the emitted code.

  • AssemblyBuilderAccess.Save

    The dynamic assembly represented by an AssemblyBuilder object is persistable but cannot be executed until the saved portable executable (PE) file has been loaded from disk.

  • AssemblyBuilderAccess.RunAndSave

    The dynamic assembly represented by an AssemblyBuilder object is persistable, but can also be executed before and/or after the assembly is saved to disk.

The access mode must be specified by providing the appropriate AssemblyBuilderAccess value in the call to the AssemblyBuilder.DefineDynamicAssembly method when the dynamic assembly is defined and cannot be changed later. The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation.

The following code example shows how to define a dynamic assembly with one module. The module in the example assembly contains one type, MyDynamicType, which has a private field, a property that gets and sets the private field, constructors that initialize the private field, and a method that multiplies a user-supplied number by the private field value and returns the result.

AssemblyBuilderAccess.RunAndSave is specified when the assembly is created. The assembly code is used immediately, and the assembly is also saved to disk so that it can be examined with Ildasm.exe (IL Disassembler) or used in another program.

using System;
using System.Reflection;
using System.Reflection.Emit;

class DemoAssemblyBuilder
{
    public static void Main()
    {
        // An assembly consists of one or more modules, each of which
        // contains zero or more types. This code creates a single-module
        // assembly, the most common case. The module contains one type,
        // named "MyDynamicType", that has a private field, a property 
        // that gets and sets the private field, constructors that 
        // initialize the private field, and a method that multiplies 
        // a user-supplied number by the private field value and returns
        // the result. In C# the type might look like this:
        /*
        public class MyDynamicType
        {
            private int m_number;

            public MyDynamicType() : this(42) {}
            public MyDynamicType(int initNumber)
            {
                m_number = initNumber;
            }

            public int Number
            {
                get { return m_number; }
                set { m_number = value; }
            }

            public int MyMethod(int multiplier)
            {
                return m_number * multiplier;
            }
        }
        */

        AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
        AssemblyBuilder ab = 
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                aName, 
                AssemblyBuilderAccess.RunAndSave);

        // For a single-module assembly, the module name is usually
        // the assembly name plus an extension.
        ModuleBuilder mb = 
            ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

        TypeBuilder tb = mb.DefineType(
            "MyDynamicType", 
             TypeAttributes.Public);

        // Add a private field of type int (Int32).
        FieldBuilder fbNumber = tb.DefineField(
            "m_number", 
            typeof(int), 
            FieldAttributes.Private);

        // Define a constructor that takes an integer argument and 
        // stores it in the private field. 
        Type[] parameterTypes = { typeof(int) };
        ConstructorBuilder ctor1 = tb.DefineConstructor(
            MethodAttributes.Public, 
            CallingConventions.Standard, 
            parameterTypes);

        ILGenerator ctor1IL = ctor1.GetILGenerator();
        // For a constructor, argument zero is a reference to the new
        // instance. Push it on the stack before calling the base
        // class constructor. Specify the default constructor of the 
        // base class (System.Object) by passing an empty array of 
        // types (Type.EmptyTypes) to GetConstructor.
        ctor1IL.Emit(OpCodes.Ldarg_0);
        ctor1IL.Emit(OpCodes.Call, 
            typeof(object).GetConstructor(Type.EmptyTypes));
        // Push the instance on the stack before pushing the argument
        // that is to be assigned to the private field m_number.
        ctor1IL.Emit(OpCodes.Ldarg_0);
        ctor1IL.Emit(OpCodes.Ldarg_1);
        ctor1IL.Emit(OpCodes.Stfld, fbNumber);
        ctor1IL.Emit(OpCodes.Ret);

        // Define a default constructor that supplies a default value
        // for the private field. For parameter types, pass the empty
        // array of types or pass null.
        ConstructorBuilder ctor0 = tb.DefineConstructor(
            MethodAttributes.Public, 
            CallingConventions.Standard, 
            Type.EmptyTypes);

        ILGenerator ctor0IL = ctor0.GetILGenerator();
        // For a constructor, argument zero is a reference to the new
        // instance. Push it on the stack before pushing the default
        // value on the stack, then call constructor ctor1.
        ctor0IL.Emit(OpCodes.Ldarg_0);
        ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
        ctor0IL.Emit(OpCodes.Call, ctor1);
        ctor0IL.Emit(OpCodes.Ret);

        // Define a property named Number that gets and sets the private 
        // field.
        //
        // The last argument of DefineProperty is null, because the
        // property has no parameters. (If you don't specify null, you must
        // specify an array of Type objects. For a parameterless property,
        // use the built-in array with no elements: Type.EmptyTypes)
        PropertyBuilder pbNumber = tb.DefineProperty(
            "Number", 
            PropertyAttributes.HasDefault, 
            typeof(int), 
            null);

        // The property "set" and property "get" methods require a special
        // set of attributes.
        MethodAttributes getSetAttr = MethodAttributes.Public | 
            MethodAttributes.SpecialName | MethodAttributes.HideBySig;

        // Define the "get" accessor method for Number. The method returns
        // an integer and has no arguments. (Note that null could be 
        // used instead of Types.EmptyTypes)
        MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
            "get_Number", 
            getSetAttr, 
            typeof(int), 
            Type.EmptyTypes);

        ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator();
        // For an instance property, argument zero is the instance. Load the 
        // instance, then load the private field and return, leaving the
        // field value on the stack.
        numberGetIL.Emit(OpCodes.Ldarg_0);
        numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
        numberGetIL.Emit(OpCodes.Ret);

        // Define the "set" accessor method for Number, which has no return
        // type and takes one argument of type int (Int32).
        MethodBuilder mbNumberSetAccessor = tb.DefineMethod(
            "set_Number", 
            getSetAttr, 
            null, 
            new Type[] { typeof(int) });

        ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();
        // Load the instance and then the numeric argument, then store the
        // argument in the field.
        numberSetIL.Emit(OpCodes.Ldarg_0);
        numberSetIL.Emit(OpCodes.Ldarg_1);
        numberSetIL.Emit(OpCodes.Stfld, fbNumber);
        numberSetIL.Emit(OpCodes.Ret);

        // Last, map the "get" and "set" accessor methods to the 
        // PropertyBuilder. The property is now complete. 
        pbNumber.SetGetMethod(mbNumberGetAccessor);
        pbNumber.SetSetMethod(mbNumberSetAccessor);

        // Define a method that accepts an integer argument and returns
        // the product of that integer and the private field m_number. This
        // time, the array of parameter types is created on the fly.
        MethodBuilder meth = tb.DefineMethod(
            "MyMethod", 
            MethodAttributes.Public, 
            typeof(int), 
            new Type[] { typeof(int) });

        ILGenerator methIL = meth.GetILGenerator();
        // To retrieve the private instance field, load the instance it
        // belongs to (argument zero). After loading the field, load the 
        // argument one and then multiply. Return from the method with 
        // the return value (the product of the two numbers) on the 
        // execution stack.
        methIL.Emit(OpCodes.Ldarg_0);
        methIL.Emit(OpCodes.Ldfld, fbNumber);
        methIL.Emit(OpCodes.Ldarg_1);
        methIL.Emit(OpCodes.Mul);
        methIL.Emit(OpCodes.Ret);

        // Finish the type.
        Type t = tb.CreateType();

        // The following line saves the single-module assembly. This
        // requires AssemblyBuilderAccess to include Save. You can now
        // type "ildasm MyDynamicAsm.dll" at the command prompt, and 
        // examine the assembly. You can also write a program that has
        // a reference to the assembly, and use the MyDynamicType type.
        // 
        ab.Save(aName.Name + ".dll");

        // Because AssemblyBuilderAccess includes Run, the code can be
        // executed immediately. Start by getting reflection objects for
        // the method and the property.
        MethodInfo mi = t.GetMethod("MyMethod");
        PropertyInfo pi = t.GetProperty("Number");

        // Create an instance of MyDynamicType using the default 
        // constructor. 
        object o1 = Activator.CreateInstance(t);

        // Display the value of the property, then change it to 127 and 
        // display it again. Use null to indicate that the property
        // has no index.
        Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));
        pi.SetValue(o1, 127, null);
        Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));

        // Call MyMethod, passing 22, and display the return value, 22
        // times 127. Arguments must be passed as an array, even when
        // there is only one.
        object[] arguments = { 22 };
        Console.WriteLine("o1.MyMethod(22): {0}", 
            mi.Invoke(o1, arguments));

        // Create an instance of MyDynamicType using the constructor
        // that specifies m_Number. The constructor is identified by
        // matching the types in the argument array. In this case, 
        // the argument array is created on the fly. Display the 
        // property value.
        object o2 = Activator.CreateInstance(t, 
            new object[] { 5280 });
        Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, null));
    }
}

/* This code produces the following output:

o1.Number: 42
o1.Number: 127
o1.MyMethod(22): 2794
o2.Number: 5280
 */

ReflectionPermission

when invoked late-bound through mechanisms such as Type.InvokeMember. Associated enumeration: ReflectionPermissionFlag.MemberAccess.

.NET Framework
Available since 1.1
Silverlight
Available since 2.0

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

Return to top
Show: