System.AppDomain Class

Assembly: Mscorlib.dll
Namespace: System
Summary
Represents an application domain, which is an isolated environment where applications execute. This class cannot be inherited.
C# Syntax:
public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory
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 class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.

For more information about using application domains, see the list of Frequently Asked Questions at gotdotnet/team/clr/appdomainfaq.aspx

This class implements the MarshalByRefObject, _AppDomain, and IEvidenceFactory interfaces.

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.
CurrentDomain Read-only

Gets the current application domain for the current Thread.
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 the 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.
SetupInformation Read-only

Gets the application domain configuration information for this instance.
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 ("").
CreateDomain Overloaded:
CreateDomain(string friendlyName)

Creates a new application domain with the specified name.
CreateDomain Overloaded:
CreateDomain(string friendlyName, Evidence securityInfo)

Creates a new application domain with the given name using the supplied evidence.
CreateDomain Overloaded:
CreateDomain(string friendlyName, Evidence securityInfo, AppDomainSetup info)

Creates a new application domain using the specified name, evidence, and application domain setup information.
CreateDomain Overloaded:
CreateDomain(string friendlyName, Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles)

Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain.
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.
CreateInstanceAndUnwrap Overloaded:
CreateInstanceAndUnwrap(string assemblyName, string typeName)

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.
CreateInstanceAndUnwrap Overloaded:
CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes)

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes.
CreateInstanceAndUnwrap Overloaded:
CreateInstanceAndUnwrap(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. Parameters specify the name of the type, and how it is found and created.
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.
CreateInstanceFromAndUnwrap Overloaded:
CreateInstanceFromAndUnwrap(string assemblyName, string typeName)

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

Creates a new instance of the specified type defined in the specified assembly file.
CreateInstanceFromAndUnwrap Overloaded:
CreateInstanceFromAndUnwrap(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 file.
CreateObjRef
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.CreateObjRef


Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
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
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
ExecuteAssembly Overloaded:
ExecuteAssembly(string assemblyFile)

Executes the assembly contained in the specified file.
ExecuteAssembly Overloaded:
ExecuteAssembly(string assemblyFile, Evidence assemblySecurity)

Executes the assembly contained in the specified file, using the specified evidence.
ExecuteAssembly Overloaded:
ExecuteAssembly(string assemblyFile, Evidence assemblySecurity, string[] args)

Executes the assembly contained in the specified file, using the specified evidence and arguments.
GetAssemblies Gets the assemblies that have been loaded into this application domain.
GetCurrentThreadId Gets the current thread identifier.
GetData Gets the value stored in the current application domain for the specified data name.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetLifetimeService
(inherited from System.MarshalByRefObject)
See base class member description: System.MarshalByRefObject.GetLifetimeService


Retrieves the current lifetime service object that controls the lifetime policy for this instance.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
InitializeLifetimeService Overridden:
Gives the AppDomain an infinite lifetime by preventing a lease from being created.
IsFinalizingForUnload Indicates whether this application domain is unloading, and the objects it contains are being finalized by the common language runtime.
Load Overloaded:
Load(AssemblyName assemblyRef)

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

Loads the Assembly with a common object file format (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 common object file format (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 common object file format (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.
SetDynamicBase Establishes the specified directory path as the location where dynamically generated files are stored and accessed.
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.
SetShadowCopyFiles Turns on shadow copying.
SetShadowCopyPath Establishes the specified directory path as the location of assemblies to be shadow copied.
SetThreadPrincipal Sets the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain.
ToString Overridden:
Obtains the String representation of this instance.
Unload Unloads the specified application domain.
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 on the default application domain when the default application domain's parent process exits.
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.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.AppDomain Member Details

Property: BaseDirectory (read-only)
Summary
Gets the base directory that the assembly resolver used to probe for assemblies.
C# Syntax:
public string BaseDirectory {get;}
Implements:
_AppDomain.BaseDirectory
Remarks
This property corresponds to the assembly resolver's APPBASE.

Return to top


Property: CurrentDomain (read-only)
Summary
Gets the current application domain for the current Thread.
C# Syntax:
public static AppDomain CurrentDomain {get;}

Return to top


Property: DynamicDirectory (read-only)
Summary
Gets the directory that the assembly resolver used to probe for dynamically-created assemblies.
C# Syntax:
public string DynamicDirectory {get;}
Implements:
_AppDomain.DynamicDirectory
Remarks
This property is only available after 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 the security policy.
C# Syntax:
public Evidence Evidence {get;}
Implements:
_AppDomain.Evidence
Implements:
IEvidenceFactory.Evidence

Return to top


Property: FriendlyName (read-only)
Summary
Gets the friendly name of this application domain.
C# Syntax:
public string FriendlyName {get;}
Implements:
_AppDomain.FriendlyName
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.
C# Syntax:
public string RelativeSearchPath {get;}
Implements:
_AppDomain.RelativeSearchPath
Remarks
Private assemblies are deployed in the same directory structure as the application.

Return to top


Property: SetupInformation (read-only)
Summary
Gets the application domain configuration information for this instance.
C# Syntax:
public AppDomainSetup SetupInformation {get;}

Return to top


Property: ShadowCopyFiles (read-only)
Summary
Gets an indication whether all assemblies loaded in the application domain are shadow copied.
C# Syntax:
public bool ShadowCopyFiles {get;}
Implements:
_AppDomain.ShadowCopyFiles
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.
C# Syntax:
public void AppendPrivatePath(
   string path
);
Parameters:

path

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

Implements:
_AppDomain.AppendPrivatePath
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 ("").
C# Syntax:
public void ClearPrivatePath();
Implements:
_AppDomain.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.

.NET Framework Security:
SecurityPermission for using this method. Associated enumeration: SecurityAction.LinkDemand.
See also:
String.Empty

Return to top


Method: ClearShadowCopyPath()
Summary
Resets the list of directories containing shadow copied assemblies to the empty string ("").
C# Syntax:
public void ClearShadowCopyPath();
Implements:
_AppDomain.ClearShadowCopyPath
Remarks
The shadow copy path is a list of directories where shadow copied assemblies are stored.

For more information, see AppDomainSetup.ShadowCopyDirectories.

.NET Framework Security:
SecurityPermission for using this method. Associated enumeration: SecurityAction.LinkDemand.
See also:
String.Empty

Return to top


Overloaded Method: CreateDomain(
   string friendlyName
)
Summary
Creates a new application domain with the specified name.
C# Syntax:
public static AppDomain CreateDomain(
   string friendlyName
);
Parameters:

friendlyName

The friendly name of the domain.

Return Value:
The newly created application domain.
Exceptions
Exception Type Condition
ArgumentNullException friendlyName is null.
Remarks
The friendlyName parameter is intended to identify the domain in a manner that is meaningful to humans. This string should be suitable for display in user interfaces.
Example
The following sample demonstrates, in general, how to create a domain using one of the AppDomain.CreateDomain overloads.
      // Set up the AppDomainSetup
      AppDomainSetup setup = new AppDomainSetup();
      setup.ApplicationBase = "(some directory)";
      setup.ConfigurationFile = "(some file)";

      // Set up the Evidence
      Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
      Evidence evidence = new Evidence(baseEvidence);
      evidence.AddAssembly("(some assembly)");
      evidence.AddHost("(some host)");

      // Create the AppDomain      
      AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);

    
.NET Framework Security:
SecurityPermission for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain
See also:
AppDomain.FriendlyName

Return to top


Overloaded Method: CreateDomain(
   string friendlyName,
   Evidence securityInfo
)
Summary
Creates a new application domain with the given name using the supplied evidence.
C# Syntax:
public static AppDomain CreateDomain(
   string friendlyName,
   Evidence securityInfo
);
Parameters:

friendlyName

The friendly name of the domain. This friendly name can be displayed in user interfaces to identify the domain. For more information, see the description of AppDomain.FriendlyName.

securityInfo

Evidence mapped through the security policy to establish a top-of-stack permission set.

Return Value:
The newly created application domain.
Example
The following sample demonstrates, in general, how to create a domain using one of the AppDomain.CreateDomain overloads.
      // Set up the AppDomainSetup
      AppDomainSetup setup = new AppDomainSetup();
      setup.ApplicationBase = "(some directory)";
      setup.ConfigurationFile = "(some file)";

      // Set up the Evidence
      Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
      Evidence evidence = new Evidence(baseEvidence);
      evidence.AddAssembly("(some assembly)");
      evidence.AddHost("(some host)");

      // Create the AppDomain      
      AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);

    
.NET Framework Security:
SecurityPermission for the ability to provide evidence, including the ability to alter the evidence provided by the common language runtime. Associated enumeration: SecurityPermissionFlag/ControlEvidence

-or-

for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain

Return to top


Overloaded Method: CreateDomain(
   string friendlyName,
   Evidence securityInfo,
   AppDomainSetup info
)
Summary
Creates a new application domain using the specified name, evidence, and application domain setup information.
C# Syntax:
public static AppDomain CreateDomain(
   string friendlyName,
   Evidence securityInfo,
   AppDomainSetup info
);
Parameters:

friendlyName

The friendly name of the domain. This friendly name can be displayed in user interfaces to identify the domain. For more information, see the description of AppDomain.FriendlyName.

securityInfo

Evidence mapped through the security policy to establish a top-of-stack permission set.

info

An object that contains application domain initialization information.

Return Value:
The newly created application domain.
Example
The following sample demonstrates, in general, how to create a domain using one of the AppDomain.CreateDomain overloads.
      // Set up the AppDomainSetup
      AppDomainSetup setup = new AppDomainSetup();
      setup.ApplicationBase = "(some directory)";
      setup.ConfigurationFile = "(some file)";

      // Set up the Evidence
      Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
      Evidence evidence = new Evidence(baseEvidence);
      evidence.AddAssembly("(some assembly)");
      evidence.AddHost("(some host)");

      // Create the AppDomain      
      AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);

    
.NET Framework Security:
SecurityPermission for the ability to provide evidence, including the ability to alter the evidence provided by the common language runtime. Associated enumeration: SecurityPermissionFlag/ControlEvidence

-or-

for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain

Return to top


Overloaded Method: CreateDomain(
   string friendlyName,
   Evidence securityInfo,
   string appBasePath,
   string appRelativeSearchPath,
   bool shadowCopyFiles
)
Summary
Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain.
C# Syntax:
public static AppDomain CreateDomain(
   string friendlyName,
   Evidence securityInfo,
   string appBasePath,
   string appRelativeSearchPath,
   bool shadowCopyFiles
);
Parameters:

friendlyName

The friendly name of the domain. This friendly name can be displayed in user interfaces to identify the domain. For more information, see the description of AppDomain.FriendlyName.

securityInfo

Evidence mapped through the security policy to establish a top-of-stack permission set.

appBasePath

The base directory that the assembly resolver uses to probe for assemblies. For more information, see the description of AppDomain.BaseDirectory.

appRelativeSearchPath

The path relative to the base directory where the assembly resolver should probe for private assemblies. For more information, see the description of AppDomain.RelativeSearchPath.

shadowCopyFiles

If true, a shadow copy of an assembly is loaded into this application domain.

Return Value:
The newly created application domain.
Example
The following sample demonstrates, in general, how to create a domain using one of the AppDomain.CreateDomain overloads.
      // Set up the AppDomainSetup
      AppDomainSetup setup = new AppDomainSetup();
      setup.ApplicationBase = "(some directory)";
      setup.ConfigurationFile = "(some file)";

      // Set up the Evidence
      Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
      Evidence evidence = new Evidence(baseEvidence);
      evidence.AddAssembly("(some assembly)");
      evidence.AddHost("(some host)");

      // Create the AppDomain      
      AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);

    
.NET Framework Security:
SecurityPermission for the ability to provide evidence, including the ability to alter the evidence provided by the common language runtime. Associated enumeration: SecurityPermissionFlag/ControlEvidence

-or-

for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain

Return to top


Overloaded Method: CreateInstance(
   string assemblyName,
   string typeName
)
Summary
Creates a new instance of the specified type defined in the specified assembly.
C# Syntax:
public 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 specified by typeName. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
MissingMethodException No matching public constructor was found.
TypeLoadException typename was not found in assemblyName.
FileNotFoundException assemblyName was not found.
MethodAccessException The caller does not have permission to call this constructor.
Implements:
_AppDomain.CreateInstance
Remarks
This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

.NET Framework Security:
SecurityPermission for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag/UnmanagedCode
.NET Framework Security:
ReflectionPermission for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag/MemberAccess
See also:
Activator.CreateInstance

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.
C# Syntax:
public 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 specified by typeName. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
MissingMethodException No matching public constructor was found.
TypeLoadException typename was not found in assemblyName.
FileNotFoundException assemblyName was not found.
MethodAccessException The caller does not have permission to call this constructor.
Implements:
_AppDomain.CreateInstance
Remarks
This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

.NET Framework Security:
SecurityPermission for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag/UnmanagedCode
.NET Framework Security:
ReflectionPermission for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag/MemberAccess
See also:
Activator.CreateInstance

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.
C# Syntax:
public 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 pass to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to invoke. If the default constructor is preferred, 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 specified by typeName. The return value needs to be unwrapped to access the real object.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
MissingMethodException No matching constructor was found.
TypeLoadException typename was not found in assemblyName.
FileNotFoundException assemblyName was not found.
MethodAccessException The caller does not have permission to call this constructor.
Implements:
_AppDomain.CreateInstance
Remarks
This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

Example
The following sample demonstrates using AppDomain.CreateInstance with a CultureInfo, and a custom binder to convert a String to a Double.
using System;
using System.Reflection;
using System.Globalization;

class MySimpleBinder : Binder {

   public override MethodBase BindToMethod(
      BindingFlags bindingAttr,
      MethodBase[] match,
      ref object[] args,
      ParameterModifier[] modifiers,
      CultureInfo culture,
      string[] names,
      out object state
   ) {
      if (args[0] is string) {
         args[0] = ChangeType(args[0], typeof(double), culture);
      }
      return Type.DefaultBinder.BindToMethod(
         bindingAttr,
         match,
         ref args,
         modifiers,
         culture,
         names,
         out state
      );
   }
   
   public override object ChangeType(
      object value,
      Type type,
      CultureInfo culture
   ) {
      return Convert.ChangeType(value, type, culture.NumberFormat);
   }

   public override FieldInfo BindToField(
      BindingFlags bindingAttr,
      FieldInfo[] match,
      object value,
      CultureInfo culture
   ) {
      throw new NotImplementedException();
   }
   
   public override MethodBase SelectMethod(
      BindingFlags bindingAttr,
      MethodBase[] match,
      Type[] types,
      ParameterModifier[] modifiers
   ) {
      throw new NotImplementedException();
   }
   
   public override PropertyInfo SelectProperty(
      BindingFlags bindingAttr,
      PropertyInfo[] match,
      Type returnType,
      Type[] indexes,
      ParameterModifier[] modifiers
   ) {
      throw new NotImplementedException();
   }
   
   public override void ReorderArgumentArray(
      ref object[] args,
      object state
   ) {
      throw new NotImplementedException();
   }
   
}

class Test {
   static void Main() {
      InstantiateDecimal(null, null);
      // Fails to instantiate

      InstantiateDecimal(new MySimpleBinder(), new CultureInfo("en-US"));
      // Instantiates new Decimal(9.999d)
      
      InstantiateDecimal(new MySimpleBinder(), new CultureInfo("de-DE"));
      // Instantiates new Decimal(9999d)
   }
   
   // Attempts instantiation of a Decimal object with a string argument
   // using the given Binder and CultureInfo object.
   static void InstantiateDecimal(Binder binder, CultureInfo cultureInfo) {
      try {
         AppDomain currentDomain = AppDomain.CurrentDomain;
         object instance = currentDomain.CreateInstanceAndUnwrap(
            "mscorlib",
            "System.Decimal",
            false,
            BindingFlags.Default,
            binder,
            new object[] { "9.999" },
            cultureInfo,
            null,
            null
         );
         Console.WriteLine(instance);
      } catch (MissingMethodException e) {
         Console.WriteLine(e.Message);
      }
   }
}

    
.NET Framework Security:
SecurityPermission for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag/UnmanagedCode
.NET Framework Security:
ReflectionPermission for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag/MemberAccess
See also:
Activator.CreateInstance

Return to top


Overloaded Method: CreateInstanceAndUnwrap(
   string assemblyName,
   string typeName
)
Summary
Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.
C# Syntax:
public object CreateInstanceAndUnwrap(
   string assemblyName,
   string typeName
);
Parameters:

assemblyName

The display name of the assembly.

typeName

The fully-qualified name of the requested type.

Return Value:
An instance of the object specified by typeName.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
MissingMethodException No matching public constructor was found.
TypeLoadException typename was not found in assemblyName.
FileNotFoundException assemblyName was not found.
MethodAccessException The caller does not have permission to call this constructor.
Remarks
This is a convenience method that combines AppDomain.CreateInstance and ObjectHandle.Unwrap. This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

.NET Framework Security:
SecurityPermission for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag/UnmanagedCode
.NET Framework Security:
ReflectionPermission for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag/MemberAccess
See also:
AppDomain.CreateInstance

Return to top


Overloaded Method: CreateInstanceAndUnwrap(
   string assemblyName,
   string typeName,
   object[] activationAttributes
)
Summary
Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes.
C# Syntax:
public object CreateInstanceAndUnwrap(
   string assemblyName,
   string typeName,
   object[] activationAttributes
);
Parameters:

assemblyName

The display name of the assembly.

typeName

The fully-qualified name of the requested type.

activationAttributes

An array containing one or more attributes that can participate in activation.

Return Value:
An instance of the object specified by typeName.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
MissingMethodException No matching public constructor was found.
TypeLoadException typename was not found in assemblyName.
FileNotFoundException assemblyName was not found.
MethodAccessException The caller does not have permission to call this constructor.
Remarks
This is a convenience method that combines AppDomain.CreateInstance and ObjectHandle.Unwrap. This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

.NET Framework Security:
SecurityPermission for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag/UnmanagedCode
.NET Framework Security:
ReflectionPermission for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag/MemberAccess
See also:
AppDomain.CreateInstance

Return to top


Overloaded Method: CreateInstanceAndUnwrap(
   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. Parameters specify the name of the type, and how it is found and created.
C# Syntax:
public object CreateInstanceAndUnwrap(
   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 pass to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to invoke. If the default constructor is preferred, args must be an empty array or null.

culture

A culture-specific object used to govern the coercion of types. If culture is null, the CultureInfo for the current thread is used.

activationAttributes

An array of one or more attributes that can participate in activation.

securityAttributes

Information used to authorize creation of typeName.

Return Value:
An instance of the object specified by typeName.
Exceptions
Exception Type Condition
ArgumentNullException assemblyName or typeName is null.
MissingMethodException No matching constructor was found.
TypeLoadException typename was not found in assemblyName.
FileNotFoundException assemblyName was not found.
MethodAccessException The caller does not have permission to call this constructor.
Remarks
This is a convenience method that combines AppDomain.CreateInstance and ObjectHandle.Unwrap. This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName.

Example
The following sample demonstrates the use of the ignoreCase parameter.
using System;
using System.Reflection;

class Test {

   static void Main() {
      InstantiateINT32(false);     // Failed!
      InstantiateINT32(true);      // OK!
   }
   
   static void InstantiateINT32(bool ignoreCase) {
      try {
         AppDomain currentDomain = AppDomain.CurrentDomain;
         object instance = currentDomain.CreateInstanceAndUnwrap(
            "mscorlib",
            "SYSTEM.INT32",
            ignoreCase,
            BindingFlags.Default,
            null,
            null,
            null,
            null,
            null
         );
         Console.WriteLine(instance.GetType());
      } catch (TypeLoadException e) {
         Console.WriteLine(e.Message);
      }
   }
}

    
.NET Framework Security:
SecurityPermission for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag/UnmanagedCode
.NET Framework Security:
ReflectionPermission for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag/MemberAccess
See also:
AppDomain.CreateInstance

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.
C# Syntax:
public 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.

Implements:
_AppDomain.CreateInstanceFrom
Remarks
The default constructor for typeName is invoked.

For more information, see the Activator.CreateInstanceFrom method.

See also:
Activator.CreateInstanceFrom

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.
C# Syntax:
public 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.

Implements:
_AppDomain.CreateInstanceFrom
Remarks
The default constructor for typeName is invoked.

For more information, see the Activator.CreateInstanceFrom method.

See also:
Activator.CreateInstanceFrom

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.
C# Syntax:
public 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 pass to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to invoke. If the default constructor is preferred, 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.

Implements:
_AppDomain.CreateInstanceFrom
Remarks
For more information, see the Activator.CreateInstanceFrom method.
See also:
Activator.CreateInstanceFrom

Return to top


Overloaded Method: CreateInstanceFromAndUnwrap(
   string assemblyName,
   string typeName
)
Summary
Creates a new instance of the specified type defined in the specified assembly file.
C# Syntax:
public object CreateInstanceFromAndUnwrap(
   string assemblyName,
   string typeName
);
Parameters:

assemblyName

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:
The requested object.

-or-

null if typeName is not found.

Exceptions
Exception Type Condition
ArgumentNullException assemblyName is null.

-or-

typeName is null.

Remarks
This is a convenience method that combines AppDomain.CreateInstanceFrom and ObjectHandle.Unwrap. This method calls the default constructor for typeName.

For more information, see the Activator.CreateInstanceFrom method.

See also:
Activator.CreateInstanceFrom

Return to top


Overloaded Method: CreateInstanceFromAndUnwrap(
   string assemblyName,
   string typeName,
   object[] activationAttributes
)
Summary
Creates a new instance of the specified type defined in the specified assembly file.
C# Syntax:
public object CreateInstanceFromAndUnwrap(
   string assemblyName,
   string typeName,
   object[] activationAttributes
);
Parameters:

assemblyName

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:
The requested object.

-or-

null if typeName is not found.

Exceptions
Exception Type Condition
ArgumentNullException assemblyName is null.

-or-

typeName is null.

Remarks
This is a convenience method that combines AppDomain.CreateInstanceFrom and ObjectHandle.Unwrap. This method calls the default constructor for typeName.

For more information, see the Activator.CreateInstanceFrom method.

See also:
Activator.CreateInstanceFrom

Return to top


Overloaded Method: CreateInstanceFromAndUnwrap(
   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 file.
C# Syntax:
public object CreateInstanceFromAndUnwrap(
   string assemblyName,
   string typeName,
   bool ignoreCase,
   BindingFlags bindingAttr,
   Binder binder,
   object[] args,
   CultureInfo culture,
   object[] activationAttributes,
   Evidence securityAttributes
);
Parameters:

assemblyName

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 pass to the constructor. This array of arguments must match in number, order, and type the parameters of the constructor to invoke. If the default constructor is preferred, 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:
The requested object.

-or-

null if typeName is not found.

Exceptions
Exception Type Condition
ArgumentNullException assemblyName is null.

-or-

typeName is null.

Remarks
This is a convenience method that combines AppDomain.CreateInstanceFrom and ObjectHandle.Unwrap.

For more information, see the Activator.CreateInstanceFrom method.

See also:
Activator.CreateInstanceFrom

Return to top


Method: CreateObjRef(
   Type requestedType
)
Inherited
See base class member description: System.MarshalByRefObject.CreateObjRef

Summary
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.
C# Syntax:
public virtual ObjRef CreateObjRef(
   Type requestedType
);
Parameters:

requestedType

The Type of the object that the new ObjRef will reference.

Return Value:
Information required to generate a proxy.
Exceptions
Exception Type Condition
RemotingException This instance is not a valid remoting object.

Return to top


Overloaded Method: DefineDynamicAssembly(
   AssemblyName name,
   AssemblyBuilderAccess access
)
Summary
Defines a dynamic assembly with the specified name and access mode.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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.
C# Syntax:
public 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.

Implements:
_AppDomain.DefineDynamicAssembly
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 callBackDelegate
)
Summary
Executes the code in another application domain that is identified by the specified delegate.
C# Syntax:
public void DoCallBack(
   CrossAppDomainDelegate callBackDelegate
);
Parameters:

callBackDelegate

A delegate that specifies a method to call.

Implements:
_AppDomain.DoCallBack
Remarks
callBackDelegate can specify a marshal-by-value, MarshalByRefObject, or ContextBoundObject.
Example
The following sample demonstrates using a static AppDomain.DoCallBack method.
   static string greetings = "PONG!";

   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");

      greetings = "PING!";

      MyCallBack();
      otherDomain.DoCallBack(new CrossAppDomainDelegate(MyCallBack));

      // Output:
      //   PING! from default domain
      //   PONG! from otherDomain
   }
   
   static void MyCallBack() {
      string name = AppDomain.CurrentDomain.FriendlyName;
      Console.WriteLine(greetings + " from " + name);
   }

    

The following sample demonstrates using the AppDomain.DoCallBack method by value.

[Serializable]
public class PingPong {
   private string greetings = "PING!";
   
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");

      PingPong pp = new PingPong();
      pp.MyCallBack();
      pp.greetings = "PONG!";
      otherDomain.DoCallBack(new CrossAppDomainDelegate(pp.MyCallBack));

      // Output:
      //   PING! from default domain
      //   PONG! from otherDomain
   }
   
   public void MyCallBack() {
      string name = AppDomain.CurrentDomain.FriendlyName;
      Console.WriteLine(greetings + " from " + name);
   }
}

    

The following sample demonstrates using the AppDomain.DoCallBack method by reference.

public class PingPong : MarshalByRefObject {
   private string greetings = "PING!";
   
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");

      PingPong pp = new PingPong();
      otherDomain.DoCallBack(new CrossAppDomainDelegate(pp.MyCallBack));
      pp.MyCallBack();


      // Output:
      //   PING! from default domain
      //   PONG! from default domain
   }
   
   public void MyCallBack() {
      string name = AppDomain.CurrentDomain.FriendlyName;
      Console.WriteLine(greetings + " from " + name);
      greetings = "PONG!";
   }
}

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

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

Return to top


Overloaded Method: ExecuteAssembly(
   string assemblyFile
)
Summary
Executes the assembly contained in the specified file.
C# Syntax:
public int ExecuteAssembly(
   string assemblyFile
);
Parameters:

assemblyFile

The name of the file that contains the assembly to execute.

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.
Implements:
_AppDomain.ExecuteAssembly
Remarks
The assembly begins executing at the entry point specified in the .NET Framework header.

This method does not create a new process or application domain, and it does not execute the entry point method on a new thread.

To create the AppDomain to load and execute, use the AppDomain.CreateDomain method.

Example
The following sample demonstrates using one of the overloads of AppDomain.ExecuteAssembly on two different domains.
class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");
      
      currentDomain.ExecuteAssembly("MyExecutable.exe");
      // Prints "MyExecutable running on [default]"

      otherDomain.ExecuteAssembly("MyExecutable.exe");
      // Prints "MyExecutable running on otherDomain"
   }
}

    

Return to top


Overloaded Method: ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity
)
Summary
Executes the assembly contained in the specified file, using the specified evidence.
C# Syntax:
public int ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity
);
Parameters:

assemblyFile

The name of the file that contains the assembly to execute.

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.
Implements:
_AppDomain.ExecuteAssembly
Remarks
The assembly begins executing at the entry point specified in the .NET Framework header.

The AppDomain.ExecuteAssembly method does not create a new process or application domain, and it does not execute the entry point method on a new thread.

Example
The following sample demonstrates using one of the overloads of AppDomain.ExecuteAssembly on two different domains.
class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");
      
      currentDomain.ExecuteAssembly("MyExecutable.exe");
      // Prints "MyExecutable running on [default]"

      otherDomain.ExecuteAssembly("MyExecutable.exe");
      // Prints "MyExecutable running on otherDomain"
   }
}

    

Return to top


Overloaded Method: ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity,
   string[] args
)
Summary
Executes the assembly contained in the specified file, using the specified evidence and arguments.
C# Syntax:
public int ExecuteAssembly(
   string assemblyFile,
   Evidence assemblySecurity,
   string[] args
);
Parameters:

assemblyFile

The name of the file that contains the assembly to execute.

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.
Implements:
_AppDomain.ExecuteAssembly
Remarks
The assembly begins executing at the entry point specified in the .NET Framework header.

This method does not create a new process or application domain, and it does not execute the entry point method on a new thread.

Example
The following sample demonstrates using one of the overloads of AppDomain.ExecuteAssembly on two different domains.
class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      AppDomain otherDomain = AppDomain.CreateDomain("otherDomain");
      
      currentDomain.ExecuteAssembly("MyExecutable.exe");
      // Prints "MyExecutable running on [default]"

      otherDomain.ExecuteAssembly("MyExecutable.exe");
      // Prints "MyExecutable running on otherDomain"
   }
}

    

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~AppDomain();

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

Return to top


Method: GetAssemblies()
Summary
Gets the assemblies that have been loaded into this application domain.
C# Syntax:
public Assembly[] GetAssemblies();
Return Value:
An array of assemblies in this application domain.
Implements:
_AppDomain.GetAssemblies

Return to top


Method: GetCurrentThreadId()
Summary
Gets the current thread identifier.
C# Syntax:
public static int GetCurrentThreadId();
Return Value:
A 32-bit signed integer that is the identifier of the current thread.
See also:
Int32

Return to top


Method: GetData(
   string name
)
Summary
Gets the value stored in the current application domain for the specified data name.
C# Syntax:
public 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.
Implements:
_AppDomain.GetData
Remarks
Use this method to retrieve the value of an entry in an internal cache of name-data pairs that describe properties of this instance of AppDomain.

The cache automatically contains predefined system entries that are inserted when the application domain is created. You can inspect their values with the AppDomain.GetData method, or the equivalent AppDomainSetup properties. You can modify their values with the appropriate AppDomainSetup properties.

You can insert or modify your own user defined name-data pairs with the AppDomain.SetData method and inspect their values with the AppDomain.GetData method.

The following table describes the name of each predefined system entry and its corresponding AppDomainSetup property.



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

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

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

Return to top


Method: GetLifetimeService()
Inherited
See base class member description: System.MarshalByRefObject.GetLifetimeService

Summary
Retrieves the current lifetime service object that controls the lifetime policy for this instance.
C# Syntax:
public object GetLifetimeService();
Return Value:
An object of type ILease used to control the lifetime policy for this instance.
Remarks
For more information about lifetime services, see the LifetimeServices class.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

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

Return to top


Overridden Method: InitializeLifetimeService()
Summary
Gives the AppDomain an infinite lifetime by preventing a lease from being created.
C# Syntax:
public override object InitializeLifetimeService();
Return Value:
Always null.
Implements:
_AppDomain.InitializeLifetimeService

Return to top


Method: IsFinalizingForUnload()
Summary
Indicates whether this application domain is unloading, and the objects it contains are being finalized by the common language runtime.
C# Syntax:
public bool IsFinalizingForUnload();
Return Value:
true if this application domain is unloading and the common language runtime has started invoking finalizers; otherwise, false.
Remarks
The finalization method for an object provides you an opportunity to perform any necessary cleanup operations before the object is garbage collected. After finalization, the object is accessible but in an invalid state and therefore unusable. Eventually, garbage collection completes and reclaims the object.

An object's finalization method is called in one of the following situations: during garbage collection, when the application domain that contains the object is unloaded, or when the common language runtime is shutting down.

While executing in your finalization method during domain unloading, you might want to access another object that is referenced by a static field and has a finalization method. However, you cannot reliably do so because the accessed object might already have been finalized.



Note An exception to this rule is the Console class, which contains static fields that reference stream objects, but is implemented specially so you can always write to the system console, even during domain unloading or system shutdown.

Use this method in an object's finalization method to determine whether the application domain that contains the object is unloading. If that is the case, you cannot reliably access any object that has a finalization method and is referenced by a static field.

See also:
Environment.HasShutdownStarted

Return to top


Overloaded Method: Load(
   AssemblyName assemblyRef
)
Summary
Loads an Assembly given its AssemblyName.
C# Syntax:
public Assembly Load(
   AssemblyName assemblyRef
);
Parameters:

assemblyRef

An object that describes the assembly to load.

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.
Implements:
_AppDomain.Load
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 a target application domain that is not the current application domain will result in a successful load of the assembly in the target application domain. Since an Assembly is not MarshalByRefObject, when this method attempts to return the Assembly for the loaded assembly to the current application domain, the common language runtime will try to load the 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 common object file format (COFF) based image containing an emitted Assembly.
C# Syntax:
public 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.
Implements:
_AppDomain.Load
Remarks
For more information, see the Remarks section of the topic.
Example
The following sample demonstrates the use of loading a raw assembly.
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      
      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
      
      InstantiateMyType(currentDomain);   // OK!
   }
   
   static void InstantiateMyType(AppDomain domain) {
      try {
         domain.CreateInstance("MyAssembly", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   // Loads the content of a file to a byte array. 
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
   
      return buffer;
   }   

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);
      
      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }
   
   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();
      
      assemblyBuilder.Save("temp.dll");
   }
}

    

Return to top


Overloaded Method: Load(
   string assemblyString
)
Summary
Loads an Assembly given its display name.
C# Syntax:
public 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.
Implements:
_AppDomain.Load
Remarks
For more information, see the Remarks section of the topic.

Return to top


Overloaded Method: Load(
   AssemblyName assemblyRef,
   Evidence assemblySecurity
)
Summary
Loads an Assembly given its AssemblyName.
C# Syntax:
public Assembly Load(
   AssemblyName assemblyRef,
   Evidence assemblySecurity
);
Parameters:

assemblyRef

An object that describes the assembly to load.

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.
Implements:
_AppDomain.Load
Remarks
For more information, see the Remarks section of the topic.

Return to top


Overloaded Method: Load(
   byte[] rawAssembly,
   byte[] rawSymbolStore
)
Summary
Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
C# Syntax:
public 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.
Implements:
_AppDomain.Load
Remarks
For more information, see the Remarks section of the topic.
Example
The following sample demonstrates the use of loading a raw assembly.
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      
      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
      
      InstantiateMyType(currentDomain);   // OK!
   }
   
   static void InstantiateMyType(AppDomain domain) {
      try {
         domain.CreateInstance("MyAssembly", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   // Loads the content of a file to a byte array. 
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
   
      return buffer;
   }   

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);
      
      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }
   
   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();
      
      assemblyBuilder.Save("temp.dll");
   }
}

    

Return to top


Overloaded Method: Load(
   string assemblyString,
   Evidence assemblySecurity
)
Summary
Loads an Assembly given its display name.
C# Syntax:
public 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.
Implements:
_AppDomain.Load
Remarks
For more information, see the Remarks section of the topic.

Return to top


Overloaded Method: Load(
   byte[] rawAssembly,
   byte[] rawSymbolStore,
   Evidence securityEvidence
)
Summary
Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded.
C# Syntax:
public 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.
Implements:
_AppDomain.Load
Remarks
For more information, see the Remarks section of the topic.
Example
The following sample demonstrates the use of loading a raw assembly.
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      
      InstantiateMyType(currentDomain);   // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
      
      InstantiateMyType(currentDomain);   // OK!
   }
   
   static void InstantiateMyType(AppDomain domain) {
      try {
         domain.CreateInstance("MyAssembly", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   // Loads the content of a file to a byte array. 
   static byte[] loadFile(string filename) {
      FileStream fs = new FileStream(filename, FileMode.Open);
      byte[] buffer = new byte[(int) fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
   
      return buffer;
   }   

   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;

      // Once the files are generated, this call is
      // actually no longer necessary.
      EmitAssembly(domain);
      
      byte[] rawAssembly = loadFile("temp.dll");
      byte[] rawSymbolStore = loadFile("temp.pdb");
      Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);

      return assembly;
   }
   
   // Creates a dynamic assembly with symbol information
   // and saves them to temp.dll and temp.pdb
   static void EmitAssembly(AppDomain domain) {
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyModule", "temp.dll", true);
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyType", TypeAttributes.Public);

      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();
      ilGenerator.EmitWriteLine("MyType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();
      
      assemblyBuilder.Save("temp.dll");
   }
}

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

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

Return to top


Method: SetAppDomainPolicy(
   PolicyLevel domainPolicy
)
Summary
Establishes the security policy level for this application domain.
C# Syntax:
public 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.
Implements:
_AppDomain.SetAppDomainPolicy
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 path
)
Summary
Establishes the specified directory path as the location where assemblies are shadow copied.
C# Syntax:
public void SetCachePath(
   string path
);
Parameters:

path

The fully-qualified path to the shadow copy location.

Implements:
_AppDomain.SetCachePath
See also:
AppDomainSetup.CachePath

Return to top


Method: SetData(
   string name,
   object data
)
Summary
Assigns the specified value to the specified application domain property.
C# Syntax:
public void SetData(
   string name,
   object data
);
Parameters:

name

The name of an application domain property.

data

The value to set the name property.

Implements:
_AppDomain.SetData
Remarks
Use this method to insert an entry, or modify the value of an entry in an internal cache of name-data pairs that describe properties of this instance of AppDomain.

The cache automatically contains predefined system entries that are inserted when the application domain is created. You cannot insert or modify system entries with this method. You can inspect their values with the AppDomain.GetData method, or the equivalent AppDomainSetup properties described in the Remarks section of the AppDomain.GetData method. You can modify their values with the appropriate AppDomainSetup properties.

You can insert or modify your own user defined name-data pairs with this method and inspect their values with the AppDomain.GetData method.

See also:
AppDomain.GetData

Return to top


Method: SetDynamicBase(
   string path
)
Summary
Establishes the specified directory path as the location where dynamically generated files are stored and accessed.
C# Syntax:
public void SetDynamicBase(
   string path
);
Parameters:

path

The fully-qualified path to where dynamic assemblies are stored.

Remarks
This method sets the AppDomainSetup.DynamicBase property of the internal AppDomainSetup associated with this instance.
.NET Framework Security:
SecurityPermission for using this method. Associated enumeration: SecurityAction.LinkDemand.
See also:
AppDomainSetup.DynamicBase

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.
C# Syntax:
public void SetPrincipalPolicy(
   PrincipalPolicy policy
);
Parameters:

policy

The type of the principal object to attach to threads.

Implements:
_AppDomain.SetPrincipalPolicy
.NET Framework Security:
SecurityPermission for using this method. Associated enumeration: SecurityAction.LinkDemand.

Return to top


Method: SetShadowCopyFiles()
Summary
Turns on shadow copying.
C# Syntax:
public void SetShadowCopyFiles();
.NET Framework Security:
SecurityPermission for using this method. Associated enumeration: SecurityAction.LinkDemand.

Return to top


Method: SetShadowCopyPath(
   string path
)
Summary
Establishes the specified directory path as the location of assemblies to be shadow copied.
C# Syntax:
public void SetShadowCopyPath(
   string path
);
Parameters:

path

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

Implements:
_AppDomain.SetShadowCopyPath
Remarks
This method sets the AppDomainSetup.ShadowCopyDirectories property of the internal AppDomainSetup associated with this instance.
.NET Framework Security:
SecurityPermission for using this method. Associated enumeration: SecurityAction.LinkDemand.

Return to top


Method: SetThreadPrincipal(
   IPrincipal principal
)
Summary
Sets the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain.
C# Syntax:
public void SetThreadPrincipal(
   IPrincipal principal
);
Parameters:

principal

The principal object to attach to threads.

Exceptions
Exception Type Condition
ArgumentNullException principal is null.
PolicyException The thread principal has already been set.
Implements:
_AppDomain.SetThreadPrincipal
.NET Framework Security:
SecurityPermission for ability to manipulate the principal object. Associated enumeration: SecurityPermissionFlag.ControlPrincipal.

Return to top


Overridden Method: ToString()
Summary
Obtains the String representation of this instance.
C# Syntax:
public override string ToString();
Return Value:
The friendly name of the application domain.
Implements:
_AppDomain.ToString
Remarks
The string representation specifies the friendly name of the application domain.

Return to top


Method: Unload(
   AppDomain domain
)
Summary
Unloads the specified application domain.
C# Syntax:
public static void Unload(
   AppDomain domain
);
Parameters:

domain

An application domain to unload.

Exceptions
Exception Type Condition
ArgumentNullException domain is null.
CannotUnloadAppDomainException domain could not be unloaded.
Remarks
A long period of time can pass before domain unloads because it might be difficult to terminate executing threads.

If the thread that invoked AppDomain.Unload is running in the domain, another thread is started to perform the unload operation. If domain cannot be unloaded, an instance of CannotUnloadAppDomainException is thrown to that thread, not the original thread that invoked AppDomain.Unload. However, if the thread that invoked AppDomain.Unload is running outside domain, that thread will receive the exception.

The threads in domain are terminated using the Thread.Abort method, which throws the thread an instance of ThreadAbortException. Although the thread should terminate promptly, it can continue executing for an unpredictable amount of time in its finally clause.

Return to top


Event: AssemblyLoad
Summary
Occurs when an assembly is loaded.
C# Syntax:
public 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.

Example
The following sample demonstrates the AppDomain.AssemblyLoad event.
using System;
using System.Reflection;

class Test {

   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.AssemblyLoad += new AssemblyLoadEventHandler(MyAssemblyLoadEventHandler);
      
      PrintLoadedAssemblies(currentDomain);
      // Lists mscorlib and this assembly
      
      currentDomain.CreateInstance("System.Windows.Forms", "System.Windows.Forms.TextBox");
      // Loads System, System.Drawing, System.Windows.Forms
      
      PrintLoadedAssemblies(currentDomain);
      // Lists all five assemblies
   }
   
   static void PrintLoadedAssemblies(AppDomain domain) {
      Console.WriteLine("LOADED ASSEMBLIES:");
      foreach (Assembly a in domain.GetAssemblies()) {
         Console.WriteLine(a.FullName);
      }
      Console.WriteLine();
   }
   
   static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) {
      Console.WriteLine("ASSEMBLY LOADED: " + args.LoadedAssembly.FullName);
      Console.WriteLine();
   }
}

    

Return to top


Event: AssemblyResolve
Summary
Occurs when the resolution of an assembly fails.
C# Syntax:
public 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.

Example
The following sample demonstrates the AppDomain.AssemblyResolve event.
public class MyType {
   public MyType() {
      Console.WriteLine("MyType instantiated!");
   }
}

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

      InstantiateMyType(currentDomain);    // Failed!

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyType(currentDomain);    // OK!
   }

   static void InstantiateMyType(AppDomain domain) {
      try {
         domain.CreateInstance("--this assembly--", "MyType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      Console.WriteLine("Resolving...");
      return typeof(MyType).Assembly;
   }
}

    

Return to top


Event: DomainUnload
Summary
Occurs when an AppDomain is about to be unloaded.
C# Syntax:
public 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 on the default application domain when the default application domain's parent process exits.
C# Syntax:
public 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.
C# Syntax:
public 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.
C# Syntax:
public event ResolveEventHandler TypeResolve;
Remarks
The AppDomain.TypeResolve event occurs when the common language runtime is unable to determine the assembly that can create the requested type. This can occur if the type is defined in a dynamic assembly, or the type is not defined in a dynamic assembly but the runtime does not know which assembly the type is defined in. The latter situation can occur when Type.GetType is called with a type name that is not qualified with the assembly name.

The ResolveEventHandler for this event can attempt to locate and create the type.

However, the AppDomain.TypeResolve event does not occur if the runtime knows it is not possible to find a type in certain assemblies. For example, this event does not occur if the type is not found in a static assembly because the runtime knows types cannot be added dynamically to static assemblies.

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

Example
The following sample demonstrates the AppDomain.TypeResolve event.
using System;
using System.Reflection;
using System.Windows.Forms;

class Test {
   public static void Main() {
      FindType("System.Windows.Forms.TextBox, System.Windows.Forms");
      // OK!

      FindType("System.Windows.Forms.TextBox");
      // Failed!

      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.TypeResolve += new ResolveEventHandler(MyResolver);
      
      FindType("System.Windows.Forms.TextBox");
      // OK!
   }

   static void FindType(string name) {
      try {
         Type t = Type.GetType(name, true);
         Console.WriteLine(t.FullName);
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }
   
   static Assembly MyResolver(object sender, ResolveEventArgs args) {
      Console.WriteLine("Returning System.Windows.Forms...");
      return typeof(TextBox).Assembly;
   }
}

    

Return to top


Event: UnhandledException
Summary
Occurs when an exception is not caught by an event handler.
C# Syntax:
public 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.

Example
The following sample demonstrates the AppDomain.UnhandledException event.
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
      
      try {
         throw new Exception("1");
      } catch (Exception e) {
         Console.WriteLine("Catch clause caught : " + e.Message);
      }

      throw new Exception("2");

      // Output:
      //   Catch clause caught : 1
      //   MyHandler caught : 2
   }
   
   static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
      Exception e = (Exception) args.ExceptionObject;
      Console.WriteLine("MyHandler caught : " + e.Message);
   }

    

Return to top


Top of page

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