System._AppDomain Interface

Assembly: Mscorlib.dll
Namespace: System
Summary
Represents an application domain, which is an isolated environment where applications execute.
This class is not CLS Compliant

C# Syntax:
[CLSCompliant(false)]
public interface _AppDomain
Remarks
Application domains, which are represented by AppDomain objects, provide isolation, unloading, and security boundaries for executing managed code.

Multiple application domains can run in a single process; however, there is not a one-to-one correlation between application domains and threads. Several threads can belong to a single application domain, and while a given thread is not confined to a single application domain, at any given time, a thread executes in a single application domain.

Application domains are created using the AppDomain.CreateDomain method. AppDomain instances are used to load and execute assemblies ( Assembly). When a AppDomain is no longer in use, it can be unloaded.

The _AppDomain interface implements a set of events to enable applications to respond when an assembly is loaded, an application domain will be unloaded, or an unhandled exception is thrown.

See also:
System Namespace

System._AppDomain Member List:

Public Properties
BaseDirectory Read-only

Gets the base directory that the assembly resolver used to probe for assemblies.
DynamicDirectory Read-only

Gets the directory that the assembly resolver used to probe for dynamically-created assemblies.
Evidence Read-only

Gets the Evidence associated with this application domain that is used as input to security policy.
FriendlyName Read-only

Gets the friendly name of this application domain.
RelativeSearchPath Read-only

Gets the path relative to the base directory where the assembly resolver should probe for private assemblies.
ShadowCopyFiles Read-only

Gets an indication whether all assemblies loaded in the application domain are shadow copied.
Public Methods
AppendPrivatePath Appends the specified name of the directory to the private path.
ClearPrivatePath Resets the path that specifies the location of private assemblies to the empty string ("").
ClearShadowCopyPath Resets the list of directories containing shadow copied assemblies to the empty string ("").
CreateInstance Overloaded:
CreateInstance(string assemblyName, string typeName)

Creates a new instance of the specified type defined in the specified assembly.
CreateInstance Overloaded:
CreateInstance(string assemblyName, string typeName, object[] activationAttributes)

Creates a new instance of the specified type defined in the specified assembly. A parameter specifies an array of activation attributes.
CreateInstance Overloaded:
CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)

Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, activation attributes, and authorization to create the type.
CreateInstanceFrom Overloaded:
CreateInstanceFrom(string assemblyFile, string typeName)

Creates a new instance of the specified type defined in the specified assembly file.
CreateInstanceFrom Overloaded:
CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes)

Creates a new instance of the specified type defined in the specified assembly file.
CreateInstanceFrom Overloaded:
CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes)

Creates a new instance of the specified type defined in the specified assembly file.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access)

Defines a dynamic assembly with the specified name and access mode.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence)

Defines a dynamic assembly using the specified name, access mode, and evidence.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir)

Defines a dynamic assembly using the specified name, access mode, and storage directory.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence)

Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)

Defines a dynamic assembly using the specified name, access mode, and permission requests.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)

Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)

Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions)

Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests.
DefineDynamicAssembly Overloaded:
DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, bool isSynchronized)

Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option.
DoCallBack Executes the code in another application domain that is identified by the specified delegate.
Equals Returns a value indicating whether this instance is equal to a specified object.
ExecuteAssembly Overloaded:
ExecuteAssembly(string assemblyFile)

Execute the Assembly given its file name. The method specified in the .NET Framework header is called.
ExecuteAssembly Overloaded:
ExecuteAssembly(string assemblyFile, Evidence assemblySecurity)

Execute the Assembly given its file name and supplied evidence.
ExecuteAssembly Overloaded:
ExecuteAssembly(string assemblyFile, Evidence assemblySecurity, string[] args)

Execute the Assembly given its file name and supplied Evidence. Optionally, the Assembly can be loaded into the domain-neutral code area for use by multiple AppDomains.
GetAssemblies Gets the assemblies that have been loaded into this application domain.
GetData Gets the value stored in the current application domain for the specified data name.
GetHashCode Returns the hash code for this instance.
GetLifetimeService Returns a lifetime service object that controls the lifetime policy for an instance that implements this interface.
GetType Gets the type of the current instance.
InitializeLifetimeService Gives the AppDomain an infinite lifetime by preventing a lease from being created.
Load Overloaded:
Load(AssemblyName assemblyRef)

Loads an Assembly given its AssemblyName.
Load Overloaded:
Load(byte[] rawAssembly)

Loads the Assembly with a COFF based image containing an emitted Assembly.
Load Overloaded:
Load(string assemblyString)

Loads an Assembly given its display name.
Load Overloaded:
Load(AssemblyName assemblyRef, Evidence assemblySecurity)

Loads an Assembly given its AssemblyName.
Load Overloaded:
Load(byte[] rawAssembly, byte[] rawSymbolStore)

Loads the Assembly with a COFF based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
Load Overloaded:
Load(string assemblyString, Evidence assemblySecurity)

Loads an Assembly given its display name.
Load Overloaded:
Load(byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence)

Loads the Assembly with a COFF based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
SetAppDomainPolicy Establishes the security policy level for this application domain.
SetCachePath Establishes the specified directory path as the location where assemblies are shadow copied.
SetData Assigns the specified value to the specified application domain property.
SetPrincipalPolicy Specifies how principal and identity objects should be attached to a thread if the thread attempts to bind to a principal while executing in this application domain.
SetShadowCopyPath Establishes the specified directory path as the location of assemblies to be shadow copied.
SetThreadPrincipal Set the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain.
ToString Obtains the String representation of this instance.
Public Events
AssemblyLoad Occurs when an assembly is loaded.
AssemblyResolve Occurs when the resolution of an assembly fails.
DomainUnload Occurs when an AppDomain is about to be unloaded.
ProcessExit Occurs when a process is about to exit.
ResourceResolve Occurs when the resolution of a resource fails.
TypeResolve Occurs when the resolution of a type fails.
UnhandledException Occurs when an exception is not caught by an event handler.

System._AppDomain Member Details

Property: BaseDirectory (read-only)
Summary
Gets the base directory that the assembly resolver used to probe for assemblies.
This class is not CLS Compliant

C# Syntax:
string BaseDirectory {get;}
Remarks
This property corresponds to the assembly resolver's APPBASE.

Return to top


Property: DynamicDirectory (read-only)
Summary
Gets the directory that the assembly resolver used to probe for dynamically-created assemblies.
This class is not CLS Compliant

C# Syntax:
string DynamicDirectory {get;}
Remarks
Only available once an attempt has been made to load an assembly into this domain.

Return to top


Property: Evidence (read-only)
Summary
Gets the Evidence associated with this application domain that is used as input to security policy.
This class is not CLS Compliant

C# Syntax:
Evidence Evidence {get;}

Return to top


Property: FriendlyName (read-only)
Summary
Gets the friendly name of this application domain.
This class is not CLS Compliant

C# Syntax:
string FriendlyName {get;}
Remarks
The friendly name of the default application domain is the name of the assembly file loaded in the application domain. The friendly name is formed by stripping the directory specification from the assembly's codebase. For example, if an assembly with the file name "c:\MyAppDirectory\MyAssembly.exe" is loaded in the default application domain, the friendly name of that application domain is "MyAssembly.exe" .

Return to top


Property: RelativeSearchPath (read-only)
Summary
Gets the path relative to the base directory where the assembly resolver should probe for private assemblies.
This class is not CLS Compliant

C# Syntax:
string RelativeSearchPath {get;}
Remarks
Private assemblies are deployed in the same directory structure as the application.

Return to top


Property: ShadowCopyFiles (read-only)
Summary
Gets an indication whether all assemblies loaded in the application domain are shadow copied.
This class is not CLS Compliant

C# Syntax:
bool ShadowCopyFiles {get;}
Remarks
For more information, see AppDomainSetup.ShadowCopyFiles.

Return to top


Method: AppendPrivatePath(
   string path
)
Summary
Appends the specified name of the directory to the private path.
This class is not CLS Compliant

C# Syntax:
void AppendPrivatePath(
   string path
);
Parameters:

path

The name of the directory to be appended to the private path.

Remarks
The private path, or relative search path, is the path relative to the base directory where the assembly resolver probes for private assemblies.

Return to top


Method: ClearPrivatePath()
Summary
Resets the path that specifies the location of private assemblies to the empty string ("").
This class is not CLS Compliant

C# Syntax:
void ClearPrivatePath();
Remarks
The private path is a path relative to the base directory that the common language runtime searches to locate private assemblies.

For more information, see AppDomainSetup.PrivateBinPath.

See also:
String.Empty

Return to top


Method: ClearShadowCopyPath()
Summary
Resets the list of directories containing shadow copied assemblies to the empty string ("").
This class is not CLS Compliant

C# Syntax:
void ClearShadowCopyPath();
Remarks
The shadow copy path is a list of directories where shadow copied assemblies are stored.

For more information, see AppDomainSetup.ShadowCopyDirectories.

See also:
String.Empty

Return to top


Overloaded Method: CreateInstance(
   string assemblyName,
   string typeName
)
Summary
Creates a new instance of the specified type defined in the specified assembly.
This class is not CLS Compliant

C# Syntax:
ObjectHandle CreateInstance(
   string assemblyName,
   string typeName
);
Parameters:

assemblyName

The display name of the assembly.

typeName

The fully-qualified name of the requested type.

Return Value:
An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
Remarks
This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

Return to top


Overloaded Method: CreateInstance(
   string assemblyName,
   string typeName,
   object[] activationAttributes
)
Summary
Creates a new instance of the specified type defined in the specified assembly. A parameter specifies an array of activation attributes.
This class is not CLS Compliant

C# Syntax:
ObjectHandle CreateInstance(
   string assemblyName,
   string typeName,
   object[] activationAttributes
);
Parameters:

assemblyName

The display name of the assembly.

typeName

The fully-qualified name of the requested type.

activationAttributes

One or more attributes that can participate in activation.

Return Value:
An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
Remarks
This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

Return to top


Overloaded Method: CreateInstance(
   string assemblyName,
   string typeName,
   bool ignoreCase,
   BindingFlags bindingAttr,
   Binder binder,
   object[] args,
   CultureInfo culture,
   object[] activationAttributes,
   Evidence securityAttributes
)
Summary
Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, activation attributes, and authorization to create the type.
This class is not CLS Compliant

C# Syntax:
ObjectHandle CreateInstance(
   string assemblyName,
   string typeName,
   bool ignoreCase,
   BindingFlags bindingAttr,
   Binder binder,
   object[] args,
   CultureInfo culture,
   object[] activationAttributes,
   Evidence securityAttributes
);
Parameters:

assemblyName

The display name of the assembly.

typeName

The fully-qualified name of the requested type.

ignoreCase

A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder

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

args

The arguments to be passed to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to be invoked. If the default constructor is desired, args must be an empty array or null.

culture

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes

One or more attributes that can participate in activation.

securityAttributes

Information used to authorize creation of typeName.

Return Value:
An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
Remarks
This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

Return to top


Overloaded Method: CreateInstanceFrom(
   string assemblyFile,
   string typeName
)
Summary
Creates a new instance of the specified type defined in the specified assembly file.
This class is not CLS Compliant

C# Syntax:
ObjectHandle CreateInstanceFrom(
   string assemblyFile,
   string typeName
);
Parameters:

assemblyFile

The name of a file that contains an assembly that defines the requested type.

typeName

The fully-qualified name of the requested type.

Return Value:
An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyFile is null.

-or-

typeName is null.

Remarks
The default constructor for typeName is invoked.

For more information, see the Activator.CreateInstanceFrom method.

Return to top


Overloaded Method: CreateInstanceFrom(
   string assemblyFile,
   string typeName,
   object[] activationAttributes
)
Summary
Creates a new instance of the specified type defined in the specified assembly file.
This class is not CLS Compliant

C# Syntax:
ObjectHandle CreateInstanceFrom(
   string assemblyFile,
   string typeName,
   object[] activationAttributes
);
Parameters:

assemblyFile

The name of a file that contains an assembly that defines the requested type.

typeName

The fully-qualified name of the requested type.

activationAttributes

One or more attributes that can participate in activation.

Return Value:
An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyFile is null.

-or-

typeName is null.

Remarks
The default constructor for typeName is invoked.

For more information, see the Activator.CreateInstanceFrom method.

Return to top


Overloaded Method: CreateInstanceFrom(
   string assemblyFile,
   string typeName,
   bool ignoreCase,
   BindingFlags bindingAttr,
   Binder binder,
   object[] args,
   CultureInfo culture,
   object[] activationAttributes,
   Evidence securityAttributes
)
Summary
Creates a new instance of the specified type defined in the specified assembly file.
This class is not CLS Compliant

C# Syntax:
ObjectHandle CreateInstanceFrom(
   string assemblyFile,
   string typeName,
   bool ignoreCase,
   BindingFlags bindingAttr,
   Binder binder,
   object[] args,
   CultureInfo culture,
   object[] activationAttributes,
   Evidence securityAttributes
);
Parameters:

assemblyFile

The name of a file that contains an assembly that defines the requested type.

typeName

The fully-qualified name of the requested type.

ignoreCase

A Boolean value specifying whether to perform a case-sensitive search or not.

bindingAttr

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

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.

args

The arguments to be passed to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to be invoked. If the default constructor is desired, args must be an empty array or null.

culture

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes

One or more attributes that can participate in activation.

securityAttributes

Information used to authorize creation of typeName.

Return Value:
An object that is a wrapper for the new instance, or null if typeName is not found. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyFile is null.

-or-

typeName is null.

Remarks
For more information, see the Activator.CreateInstanceFrom method.

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access
)
Summary
Defines a dynamic assembly with the specified name and access mode.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The access mode for the dynamic assembly.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   Evidence evidence
)
Summary
Defines a dynamic assembly using the specified name, access mode, and evidence.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   Evidence evidence
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

evidence

The evidence supplied for the dynamic assembly.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
Only fully trusted callers can supply their evidence when defining a dynamic Assembly. The runtime will map the Evidence through the security policy to determine the granted permissions. Partially trusted callers must supply a null evidence. If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir
)
Summary
Defines a dynamic assembly using the specified name, access mode, and storage directory.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

dir

The name of the directory where the assembly will be saved. If dir is null, the directory defaults to the current directory.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   Evidence evidence
)
Summary
Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   Evidence evidence
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

dir

The name of the directory where the assembly will be saved. If dir is null, the directory defaults to the current directory.

evidence

The evidence supplied for the dynamic assembly.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
Only fully trusted callers can supply their evidence when defining a dynamic Assembly. The runtime will map the Evidence through the security policy to determine the granted permissions. Partially trusted callers must supply a null evidence. If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
)
Summary
Defines a dynamic assembly using the specified name, access mode, and permission requests.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

requiredPermissions

The required permissions request.

optionalPermissions

The optional permissions request.

refusedPermissions

The refused permissions request.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   Evidence evidence,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
)
Summary
Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   Evidence evidence,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

evidence

The evidence supplied for the dynamic assembly.

requiredPermissions

The required permissions request.

optionalPermissions

The optional permissions request.

refusedPermissions

The refused permissions request.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
Only fully trusted callers can supply their evidence when defining a dynamic Assembly. The runtime will map the Evidence through the security policy to determine the granted permissions. Partially trusted callers must supply a null evidence. If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
)
Summary
Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

dir

The name of the directory where the assembly will be saved. If dir is null, the directory defaults to the current directory.

requiredPermissions

The required permissions request.

optionalPermissions

The optional permissions request.

refusedPermissions

The refused permissions request.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   Evidence evidence,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
)
Summary
Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   Evidence evidence,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

dir

The name of the directory where the assembly will be saved. If dir is null, the directory defaults to the current directory.

evidence

The evidence supplied for the dynamic assembly.

requiredPermissions

The required permissions request.

optionalPermissions

The optional permissions request.

refusedPermissions

The refused permissions request.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
Only fully trusted callers can supply their evidence when defining a dynamic Assembly. The runtime will map the Evidence through the security policy to determine the granted permissions. Partially trusted callers must supply a null evidence. If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.

The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   Evidence evidence,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions,
   bool isSynchronized
)
Summary
Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option.
This class is not CLS Compliant

C# Syntax:
AssemblyBuilder DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access,
   string dir,
   Evidence evidence,
   PermissionSet requiredPermissions,
   PermissionSet optionalPermissions,
   PermissionSet refusedPermissions,
   bool isSynchronized
);
Parameters:

name

The unique identity of the dynamic assembly.

access

The mode in which the dynamic assembly will be accessed.

dir

The name of the directory where the dynamic assembly will be saved. If dir is null, the directory defaults to the current directory.

evidence

The evidence supplied for the dynamic assembly.

requiredPermissions

The required permissions request.

optionalPermissions

The optional permissions request.

refusedPermissions

The refused permissions request.

isSynchronized

true to synchronize the creation of modules, types, and members in the dynamic assembly; otherwise, false.true to synchronize the creation of modules, types, and members in the dynamic assembly; otherwise, false.

Return Value:
Represents the dynamic assembly created.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
ArgumentException The Name property of name is null.

-or-

The Name property of name begins with white space, or contains a forward or backward slash.

Remarks
Only fully trusted callers can supply their evidence when defining a dynamic Assembly. The runtime will map the Evidence through the security policy to determine the granted permissions. Partially trusted callers must supply null for the evidence parameter. If evidence is null, the runtime copies the permission sets, that is, the current grant and deny sets, from the caller's Assembly to the dynamic Assembly being defined and marks policy as resolved.

If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.

The name parameter indirectly specifies a Version object (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. That is, for example, if the Assembly.LoadFrom method is used to indirectly recover the Version object for this assembly, only that object's major and minor version numbers will be as originally specified.

Example
The following sample demonstrates the AppDomain.DefineDynamicAssembly method and AppDomain.AssemblyResolve event.
using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      InstantiateMyDynamicType(currentDomain);   // Failed!
      
      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
      
      InstantiateMyDynamicType(currentDomain);   // OK!
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      return DefineDynamicAssembly((AppDomain) sender);
   }
   
   static Assembly DefineDynamicAssembly(AppDomain domain) {
      // Build a dynamic assembly using Reflection Emit API.
   
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      
      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}

    

Return to top


Method: DoCallBack(
   CrossAppDomainDelegate theDelegate
)
Summary
Executes the code in another application domain that is identified by the specified delegate.
This class is not CLS Compliant

C# Syntax:
void DoCallBack(
   CrossAppDomainDelegate theDelegate
);
Parameters:

theDelegate

A delegate that specifies a method to call.

Remarks
theDelegate can specify a marshal-by-value, MarshalByRefObject, or ContextBoundObject object.

Return to top


Method: Equals(
   object other
)
Summary
Returns a value indicating whether this instance is equal to a specified object.
This class is not CLS Compliant

C# Syntax:
bool Equals(
   object other
);
Parameters:

other

An object to compare with this instance, or null.

Return Value:
true if other is an instance of AppDomain and equals the value of this instance; otherwise, false.

Return to top


Overloaded Method: ExecuteAssembly(
   string assemblyFile
)
Summary
Execute the Assembly given its file name. The method specified in the .NET Framework header is called.
This class is not CLS Compliant

C# Syntax:
int ExecuteAssembly(
   string assemblyFile
);
Parameters:

assemblyFile

The file name of the the assembly to be executed.

Return Value:
The value returned by the entry point of the assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyFile is null.
FileNotFoundException assemblyFile is not found.
BadImageFormatException assemblyFile is not a valid assembly.
Remarks
The method does not spawn a new process, create a new application domain, or create a new thread on which the entry point method is executed. To create the AppDomain to be loaded and executed, use the AppDomain.CreateDomain method.

Return to top


Overloaded Method: ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity
)
Summary
Execute the Assembly given its file name and supplied evidence.
This class is not CLS Compliant

C# Syntax:
int ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity
);
Parameters:

assemblyFile

The name of the file from which the assembly is to be loaded.

assemblySecurity

Evidence for loading the assembly.

Return Value:
The value returned by the entry point of the assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyFile is null.
FileNotFoundException assemblyFile is not found.
BadImageFormatException assemblyFile is not a valid assembly.
Remarks
The method does not spawn a new process, create a new application domain, or execute the entry point method on a new thread.

Return to top


Overloaded Method: ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity,
   string[] args
)
Summary
Execute the Assembly given its file name and supplied Evidence. Optionally, the Assembly can be loaded into the domain-neutral code area for use by multiple AppDomains.
This class is not CLS Compliant

C# Syntax:
int ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity,
   string[] args
);
Parameters:

assemblyFile

The name of the file from which the assembly is to be loaded.

assemblySecurity

The supplied evidence for the assembly.

args

The arguments to the entry point of the assembly.

Return Value:
The value returned by the entry point of the assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyFile is null.
FileNotFoundException assemblyFile is not found.
BadImageFormatException assemblyFile is not a valid assembly.
Remarks
The method does not spawn a new process, create a new application domain, or execute the entry point method on a new thread.

Return to top


Method: GetAssemblies()
Summary
Gets the assemblies that have been loaded into this application domain.
This class is not CLS Compliant

C# Syntax:
Assembly[] GetAssemblies();
Return Value:
An array of assemblies in this application domain.

Return to top


Method: GetData(
   string name
)
Summary
Gets the value stored in the current application domain for the specified data name.
This class is not CLS Compliant

C# Syntax:
object GetData(
   string name
);
Parameters:

name

The name of an application domain property.

Return Value:
The value of the name property.
Exceptions
Exception Type Condition
ArgumentNullException name is null.
Remarks
name can be the value of one of the AppDomainSetup properties.

Return to top


Method: GetHashCode()
Summary
Returns the hash code for this instance.
This class is not CLS Compliant

C# Syntax:
int GetHashCode();
Return Value:
A hash code for this instance.
See also:
Object.GetHashCode

Return to top


Method: GetLifetimeService()
Summary
Returns a lifetime service object that controls the lifetime policy for an instance that implements this interface.
This class is not CLS Compliant

C# Syntax:
object GetLifetimeService();
Return Value:
An object to control the lifetime service. This is an object of type ILease for the default lifetime service.

Return to top


Method: GetType()
Summary
Gets the type of the current instance.
This class is not CLS Compliant

C# Syntax:
Type GetType();
Return Value:
A Type object.

Return to top


Method: InitializeLifetimeService()
Summary
Gives the AppDomain an infinite lifetime by preventing a lease from being created.
This class is not CLS Compliant

C# Syntax:
object InitializeLifetimeService();
Return Value:
Always null.

Return to top


Overloaded Method: Load(
   AssemblyName assemblyRef
)
Summary
Loads an Assembly given its AssemblyName.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   AssemblyName assemblyRef
);
Parameters:

assemblyRef

An object that describes the assembly to be loaded.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyRef is null
FileNotFoundException assemblyRef is not found.
BadImageFormatException assemblyRef is not a valid assembly.
Remarks
This method should only be used to load an assembly into the current application domain. This method is defined for interoperability callers who cannot call the static Assembly.Load method.

An attempt to call AppDomain.Load on an application domain that is not the current application domain will result in a successful load of the assembly in the target application domain. Since Assembly objects are not MarshalByRef, when the method attempts to return the Assembly object for the loaded assembly to the current application domain, the runtime will try to load the specified assembly into the current application domain and the load might fail. The assembly that is loaded into the current application domain might be different from the assembly that was loaded first if the path settings for the two application domains are different.

Return to top


Overloaded Method: Load(
   byte[] rawAssembly
)
Summary
Loads the Assembly with a COFF based image containing an emitted Assembly.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   byte[] rawAssembly
);
Parameters:

rawAssembly

An array of type byte that is a COFF-based image containing an emitted assembly.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException rawAssembly is null.
BadImageFormatException rawAssembly is not a valid assembly.
Remarks
This method should only be used to load an assembly into the current application domain. This method is defined for interoperability callers who cannot call the static Assembly.Load method.

An attempt to call AppDomain.Load on an application domain that is not the current application domain will result in a successful load of the assembly in the target application domain. Since Assembly objects are not MarshalByRef, when the method attempts to return the Assembly object for the loaded assembly to the current application domain, the runtime will try to load the specified assembly into the current application domain and the load might fail. The assembly that is loaded into the current application domain might be different from the assembly that was loaded first if the path settings for the two application domains are different.

Return to top


Overloaded Method: Load(
   string assemblyString
)
Summary
Loads an Assembly given its display name.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   string assemblyString
);
Parameters:

assemblyString

The display name of the assembly.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyString is null
FileNotFoundException assemblyString is not found.
BadImageFormatException assemblyString is not a valid assembly.
Remarks
This method should only be used to load an assembly into the current application domain. This method is defined for interoperability callers who cannot call the static Assembly.Load method.

An attempt to call AppDomain.Load on an application domain that is not the current application domain will result in a successful load of the assembly in the target application domain. Since Assembly objects are not MarshalByRef, when the method attempts to return the Assembly object for the loaded assembly to the current application domain, the runtime will try to load the specified assembly into the current application domain and the load might fail. The assembly that is loaded into the current application domain might be different from the assembly that was loaded first if the path settings for the two application domains are different.

Return to top


Overloaded Method: Load(
   AssemblyName assemblyRef,
   Evidence assemblySecurity
)
Summary
Loads an Assembly given its AssemblyName.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   AssemblyName assemblyRef,
   Evidence assemblySecurity
);
Parameters:

assemblyRef

An object that describes the assembly to be loaded.

assemblySecurity

Evidence for loading the assembly.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyRef is null
FileNotFoundException assemblyRef is not found.
BadImageFormatException assemblyRef is not a valid assembly.

Return to top


Overloaded Method: Load(
   byte[] rawAssembly,
   byte[] rawSymbolStore
)
Summary
Loads the Assembly with a COFF based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   byte[] rawAssembly,
   byte[] rawSymbolStore
);
Parameters:

rawAssembly

An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore

An array of type byte containing the raw bytes representing the symbols for the assembly.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException rawAssembly is null.
BadImageFormatException rawAssembly is not a valid assembly.
Remarks
This method should only be used to load an assembly into the current application domain. This method is defined for interoperability callers who cannot call the static Assembly.Load method.

An attempt to call AppDomain.Load on an application domain that is not the current application domain will result in a successful load of the assembly in the target application domain. Since Assembly objects are not MarshalByRef, when the method attempts to return the Assembly object for the loaded assembly to the current application domain, the runtime will try to load the specified assembly into the current application domain and the load might fail. The assembly that is loaded into the current application domain might be different from the assembly that was loaded first if the path settings for the two application domains are different.

Return to top


Overloaded Method: Load(
   string assemblyString,
   Evidence assemblySecurity
)
Summary
Loads an Assembly given its display name.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   string assemblyString,
   Evidence assemblySecurity
);
Parameters:

assemblyString

The display name of the assembly.

assemblySecurity

Evidence for loading the assembly.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException assemblyString is null
FileNotFoundException assemblyString is not found.
BadImageFormatException assemblyString is not a valid assembly.

Return to top


Overloaded Method: Load(
   byte[] rawAssembly,
   byte[] rawSymbolStore,
   Evidence securityEvidence
)
Summary
Loads the Assembly with a COFF based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
This class is not CLS Compliant

C# Syntax:
Assembly Load(
   byte[] rawAssembly,
   byte[] rawSymbolStore,
   Evidence securityEvidence
);
Parameters:

rawAssembly

An array of type byte that is a COFF-based image containing an emitted assembly.

rawSymbolStore

An array of type byte containing the raw bytes representing the symbols for the assembly.

securityEvidence

Evidence for loading the assembly.

Return Value:
The loaded assembly.
Exceptions
Exception Type Condition
ArgumentNullException rawAssembly is null.
BadImageFormatException rawAssembly is not a valid assembly.
Remarks
This method should only be used to load an assembly into the current application domain. This method is defined for interoperability callers who cannot call the static Assembly.Load method.

An attempt to call AppDomain.Load on an application domain that is not the current application domain will result in a successful load of the assembly in the target application domain. Since Assembly objects are not MarshalByRef, when the method attempts to return the Assembly object for the loaded assembly to the current application domain, the runtime will try to load the specified assembly into the current application domain and the load might fail. The assembly that is loaded into the current application domain might be different from the assembly that was loaded first if the path settings for the two application domains are different.

Return to top


Method: SetAppDomainPolicy(
   PolicyLevel domainPolicy
)
Summary
Establishes the security policy level for this application domain.
This class is not CLS Compliant

C# Syntax:
void SetAppDomainPolicy(
   PolicyLevel domainPolicy
);
Parameters:

domainPolicy

The security policy level.

Exceptions
Exception Type Condition
ArgumentNullException domainPolicy is null.
PolicyException The security policy level has already been set.
Remarks
Call this method before an assembly is loaded into the AppDomain in order for the security policy to have effect.

Return to top


Method: SetCachePath(
   string s
)
Summary
Establishes the specified directory path as the location where assemblies are shadow copied.
This class is not CLS Compliant

C# Syntax:
void SetCachePath(
   string s
);
Parameters:

s

The fully-qualified path to the shadow copy location.

See also:
AppDomainSetup.CachePath

Return to top


Method: SetData(
   string name,
   object data
)
Summary
Assigns the specified value to the specified application domain property.
This class is not CLS Compliant

C# Syntax:
void SetData(
   string name,
   object data
);
Parameters:

name

The name of an application domain property.

data

The value to set the name property.

Remarks
This method has been superseded by properties of the AppDomainSetup class. The following table shows the AppDomainSetup property that corresponds to a value of name.

Value of 'name' Property
"APPBASE" ApplicationBase
"APP_CONFIG_FILE" ConfigurationFile
"DYNAMIC_BASE" DynamicBase
"DEV_PATH" (no property)
"APP_NAME" ApplicationName
"CACHE_BASE" PrivateBinPath
"BINPATH_PROBE_ONLY" PrivateBinPathProbe
"SHADOW_COPY_DIRS" ShadowCopyDirectories
"FORCE_CACHE_INSTALL" ShadowCopyFiles
"CACHE_BASE" CachePath
(application specific) LicenseFile

Return to top


Method: SetPrincipalPolicy(
   PrincipalPolicy policy
)
Summary
Specifies how principal and identity objects should be attached to a thread if the thread attempts to bind to a principal while executing in this application domain.
This class is not CLS Compliant

C# Syntax:
void SetPrincipalPolicy(
   PrincipalPolicy policy
);
Parameters:

policy

The type of the principal object to be attached to threads.

Return to top


Method: SetShadowCopyPath(
   string s
)
Summary
Establishes the specified directory path as the location of assemblies to be shadow copied.
This class is not CLS Compliant

C# Syntax:
void SetShadowCopyPath(
   string s
);
Parameters:

s

A list of directory names, where each name is separated by a semicolon.

Remarks
This method sets the AppDomainSetup.ShadowCopyDirectories property of the internal AppDomainSetup object associated with this instance.

Return to top


Method: SetThreadPrincipal(
   IPrincipal principal
)
Summary
Set the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain.
This class is not CLS Compliant

C# Syntax:
void SetThreadPrincipal(
   IPrincipal principal
);
Parameters:

principal

The principal object to be attached to threads.

Exceptions
Exception Type Condition
ArgumentNullException principal is null.
PolicyException The thread principal has already been set.

Return to top


Method: ToString()
Summary
Obtains the String representation of this instance.
This class is not CLS Compliant

C# Syntax:
string ToString();
Return Value:
The friendly name of the application domain.
Remarks
The string representation specifies the friendly name of the application domain.

Return to top


Event: AssemblyLoad
Summary
Occurs when an assembly is loaded.
This class is not CLS Compliant

C# Syntax:
event AssemblyLoadEventHandler AssemblyLoad;
Remarks
The AssemblyLoadEventHandler delegate for this event can attempt to locate the assembly and load it.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Event: AssemblyResolve
Summary
Occurs when the resolution of an assembly fails.
This class is not CLS Compliant

C# Syntax:
event ResolveEventHandler AssemblyResolve;
Remarks
It is the responsibility of ResolveEventHandler for this event to return the assembly that resolves the type, assembly, or resource.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Event: DomainUnload
Summary
Occurs when an AppDomain is about to be unloaded.
This class is not CLS Compliant

C# Syntax:
event EventHandler DomainUnload;
Remarks
The EventHandler delegate for this event can perform any termination activities before the application domain is unloaded.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Event: ProcessExit
Summary
Occurs when a process is about to exit.
This class is not CLS Compliant

C# Syntax:
event EventHandler ProcessExit;
Remarks
The EventHandler for this event can perform termination activities, such as closing files, releasing storage and so on, before the process ends.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Event: ResourceResolve
Summary
Occurs when the resolution of a resource fails.
This class is not CLS Compliant

C# Syntax:
event ResolveEventHandler ResourceResolve;
Remarks
The ResolveEventHandler for this event can attempt to locate the resource and load it.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Event: TypeResolve
Summary
Occurs when the resolution of a type fails.
This class is not CLS Compliant

C# Syntax:
event ResolveEventHandler TypeResolve;
Remarks
The ResolveEventHandler for this event can attempt to locate the type and load it.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Event: UnhandledException
Summary
Occurs when an exception is not caught by an event handler.
This class is not CLS Compliant

C# Syntax:
event UnhandledExceptionEventHandler UnhandledException;
Remarks
The UnhandledExceptionEventHandler delegate for this event provides default handling for uncaught exceptions. When this event is not handled, the system default handler reports the exception to the user and terminates the application.

This event occurs only for the application domain that is created by the system when an application is started. If an application creates additional application domains, specifying a delegate for this event in those applications domains has no effect.

For more information about handling events, see the conceptual topic at MSDN: eventsoverview.

Return to top


Top of page

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