This documentation is archived and is not being maintained.

AppDomain.CreateInstanceAndUnwrap Method (String, String, Object[])

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.

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

public Object CreateInstanceAndUnwrap(
	string assemblyName,
	string typeName,
	Object[] activationAttributes


Type: System.String
The display name of the assembly. See Assembly.FullName.
Type: System.String
The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the Type.FullName property.
Type: System.Object[]
An array of one or more attributes that can participate in activation. Typically, an array that contains a single UrlAttribute object. The UrlAttribute specifies the URL that is required to activate a remote object.

Return Value

Type: System.Object
An instance of the object specified by typeName.


assemblyName or typeName is null.


No matching public constructor was found.


typename was not found in assemblyName.


assemblyName was not found.


The caller does not have permission to call this constructor.


The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.


The operation is attempted on an unloaded application domain.


assemblyName is not a valid assembly.


Version 2.0 or later of the common language runtime is currently loaded and assemblyName was compiled with a later version.


An assembly or module was loaded twice with two different evidences.

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

See AssemblyName for the format of assemblyName. See the Type.FullName property for the format of typeName.

The activationAttributes parameter is related to client-activated objects; see Client Activation.


If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. If the current domain is the default domain, assembly C cannot be unloaded until the process ends. If the current domain later attempts to load assembly C, the load might fail.

using System;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Remoting;

class ADDyno


   public static Type CreateADynamicAssembly(ref AppDomain myNewDomain,
					     string executableNameNoExe)

	string executableName = executableNameNoExe + ".exe";

	AssemblyName myAsmName = new AssemblyName();
	myAsmName.Name = executableNameNoExe;
	myAsmName.CodeBase = Environment.CurrentDirectory;

	AssemblyBuilder myAsmBuilder = myNewDomain.DefineDynamicAssembly(myAsmName,
	Console.WriteLine("-- Dynamic Assembly instantiated.");

	ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(executableNameNoExe,

	TypeBuilder myTypeBuilder = myModBuilder.DefineType(executableNameNoExe,

	MethodBuilder myFCMethod = myTypeBuilder.DefineMethod("CountLocalFiles",
						MethodAttributes.Public |
						new Type[] {  });

	MethodInfo currentDirGetMI = typeof(Environment).GetProperty("CurrentDirectory").GetGetMethod();
	MethodInfo writeLine0objMI = typeof(Console).GetMethod("WriteLine",
				     new Type[] { typeof(string) });
	MethodInfo writeLine2objMI = typeof(Console).GetMethod("WriteLine",
				     new Type[] { typeof(string), typeof(object), typeof(object) });
	MethodInfo getFilesMI = typeof(Directory).GetMethod("GetFiles", 
				new Type[] { typeof(string) });

	myFCMethod.InitLocals = true;

	ILGenerator myFCIL = myFCMethod.GetILGenerator();

	Console.WriteLine("-- Generating MSIL method body...");
	LocalBuilder v0 = myFCIL.DeclareLocal(typeof(string));
	LocalBuilder v1 = myFCIL.DeclareLocal(typeof(int));
	LocalBuilder v2 = myFCIL.DeclareLocal(typeof(string));
	LocalBuilder v3 = myFCIL.DeclareLocal(typeof(string[]));

	Label evalForEachLabel = myFCIL.DefineLabel();
	Label topOfForEachLabel = myFCIL.DefineLabel();

	// Build the method body.

	myFCIL.EmitCall(OpCodes.Call, currentDirGetMI, null);
	myFCIL.Emit(OpCodes.Stloc_S, v0);
	myFCIL.Emit(OpCodes.Stloc_S, v1);
	myFCIL.Emit(OpCodes.Ldstr, "---");
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);
	myFCIL.Emit(OpCodes.Ldloc_S, v0);
	myFCIL.EmitCall(OpCodes.Call, getFilesMI, null);
	myFCIL.Emit(OpCodes.Stloc_S, v3);

	myFCIL.Emit(OpCodes.Br_S, evalForEachLabel);

	// foreach loop starts here.
        // Load array of strings and index, store value at index for output.
	myFCIL.Emit(OpCodes.Ldloc_S, v3);
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Stloc_S, v2);

	myFCIL.Emit(OpCodes.Ldloc_S, v2);
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);

	// Increment counter by one.
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Stloc_S, v1);

	// Determine if end of file list array has been reached.
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldloc_S, v3);
	myFCIL.Emit(OpCodes.Blt_S, topOfForEachLabel);
	//foreach loop end here.

	myFCIL.Emit(OpCodes.Ldstr, "---");
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);
	myFCIL.Emit(OpCodes.Ldstr, "There are {0} files in {1}.");
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Box, typeof(int));
	myFCIL.Emit(OpCodes.Ldloc_S, v0);
	myFCIL.EmitCall(OpCodes.Call, writeLine2objMI, null);


	Type myType = myTypeBuilder.CreateType();

	Console.WriteLine("-- Method generated, type completed, and assembly saved to disk."); 

	return myType;


   public static void Main() 

	string domainDir, executableName = null;
	Console.Write("Enter a name for the file counting assembly: ");
	string executableNameNoExe = Console.ReadLine();
	executableName = executableNameNoExe + ".exe";

	domainDir = Environment.CurrentDirectory;

	AppDomain curDomain = Thread.GetDomain();	

	// Create a new AppDomain, with the current directory as the base.

	Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory);
	AppDomainSetup mySetupInfo = new AppDomainSetup();
	mySetupInfo.ApplicationBase = domainDir;
	mySetupInfo.ApplicationName = executableNameNoExe;
	mySetupInfo.LoaderOptimization = LoaderOptimization.SingleDomain;

	AppDomain myDomain = AppDomain.CreateDomain(executableNameNoExe,
					null, mySetupInfo);

	Console.WriteLine("Creating a new AppDomain '{0}'...",

	Console.WriteLine("-- Base Directory = '{0}'", myDomain.BaseDirectory); 
	Console.WriteLine("-- Shadow Copy? = '{0}'", myDomain.ShadowCopyFiles); 

	Type myFCType = CreateADynamicAssembly(ref curDomain, 

	Console.WriteLine("Loading '{0}' from '{1}'...", executableName,

	BindingFlags bFlags = (BindingFlags.Public | BindingFlags.CreateInstance |

	Object myObjInstance = myDomain.CreateInstanceAndUnwrap(executableNameNoExe,
				executableNameNoExe, false, bFlags, 
				null, null, null, null, null);

	Console.WriteLine("Executing method 'CountLocalFiles' in {0}...",

	myFCType.InvokeMember("CountLocalFiles", BindingFlags.InvokeMethod, null,
				myObjInstance, new object[] { });


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

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