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


The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

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 Function CreateInstanceAndUnwrap (
	assemblyName As String,
	typeName As String,
	activationAttributes As Object()
) As Object


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 that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects.Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Return Value

Type: System.Object

An instance of the object specified by typeName.

Exception Condition

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.


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.

Imports System
Imports System.IO
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Runtime.Remoting

Class ADDyno

   Public Shared Function CreateADynamicAssembly(ByRef myNewDomain As AppDomain, executableNameNoExe As String) As Type

      Dim executableName As String = executableNameNoExe + ".exe"

      Dim myAsmName As New AssemblyName()
      myAsmName.Name = executableNameNoExe
      myAsmName.CodeBase = Environment.CurrentDirectory

      Dim myAsmBuilder As AssemblyBuilder = myNewDomain.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.RunAndSave)
      Console.WriteLine("-- Dynamic Assembly instantiated.")

      Dim myModBuilder As ModuleBuilder = myAsmBuilder.DefineDynamicModule(executableNameNoExe, executableName)

      Dim myTypeBuilder As TypeBuilder = myModBuilder.DefineType(executableNameNoExe, TypeAttributes.Public, GetType(MarshalByRefObject))

      Dim myFCMethod As MethodBuilder = myTypeBuilder.DefineMethod("CountLocalFiles", MethodAttributes.Public Or MethodAttributes.Static, Nothing, New Type() {})

      Dim currentDirGetMI As MethodInfo = GetType(Environment).GetProperty("CurrentDirectory").GetGetMethod()
      Dim writeLine0objMI As MethodInfo = GetType(Console).GetMethod("WriteLine", New Type() {GetType(String)})
      Dim writeLine2objMI As MethodInfo = GetType(Console).GetMethod("WriteLine", New Type() {GetType(String), GetType(Object), GetType(Object)})
      Dim getFilesMI As MethodInfo = GetType(Directory).GetMethod("GetFiles", New Type() {GetType(String)})

      myFCMethod.InitLocals = True

      Dim myFCIL As ILGenerator = myFCMethod.GetILGenerator()

      Console.WriteLine("-- Generating MSIL method body...")
      Dim v0 As LocalBuilder = myFCIL.DeclareLocal(GetType(String))
      Dim v1 As LocalBuilder = myFCIL.DeclareLocal(GetType(Integer))
      Dim v2 As LocalBuilder = myFCIL.DeclareLocal(GetType(String))
      Dim v3 As LocalBuilder = myFCIL.DeclareLocal(GetType(String()))

      Dim evalForEachLabel As Label = myFCIL.DefineLabel()
      Dim topOfForEachLabel As Label = myFCIL.DefineLabel()

      ' Build the method body.
      myFCIL.EmitCall(OpCodes.Call, currentDirGetMI, Nothing)
      myFCIL.Emit(OpCodes.Stloc_S, v0)
      myFCIL.Emit(OpCodes.Stloc_S, v1)
      myFCIL.Emit(OpCodes.Ldstr, "---")
      myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, Nothing)
      myFCIL.Emit(OpCodes.Ldloc_S, v0)
      myFCIL.EmitCall(OpCodes.Call, getFilesMI, Nothing)
      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, Nothing)

      ' 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, Nothing)
      myFCIL.Emit(OpCodes.Ldstr, "There are {0} files in {1}.")
      myFCIL.Emit(OpCodes.Ldloc_S, v1)
      myFCIL.Emit(OpCodes.Box, GetType(Integer))
      myFCIL.Emit(OpCodes.Ldloc_S, v0)
      myFCIL.EmitCall(OpCodes.Call, writeLine2objMI, Nothing)


      Dim myType As Type = myTypeBuilder.CreateType()

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

      Return myType
   End Function 'CreateADynamicAssembly

   Public Shared Sub Main()

      Dim executableName As String = Nothing
      Dim domainDir As String

      Console.Write("Enter a name for the file counting assembly: ")
      Dim executableNameNoExe As String = Console.ReadLine()
      executableName = executableNameNoExe + ".exe"

      domainDir = Environment.CurrentDirectory

      Dim curDomain As AppDomain = Thread.GetDomain()

      ' Create a new AppDomain, with the current directory as the base.
      Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory)
      Dim mySetupInfo As New AppDomainSetup()
      mySetupInfo.ApplicationBase = domainDir
      mySetupInfo.ApplicationName = executableNameNoExe
      mySetupInfo.LoaderOptimization = LoaderOptimization.SingleDomain

      Dim myDomain As AppDomain = AppDomain.CreateDomain(executableNameNoExe, Nothing, mySetupInfo)

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

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

      Dim myFCType As Type = CreateADynamicAssembly(curDomain, executableNameNoExe)

      Console.WriteLine("Loading '{0}' from '{1}'...", executableName, myDomain.BaseDirectory.ToString())

      Dim bFlags As BindingFlags = BindingFlags.Public Or BindingFlags.CreateInstance Or BindingFlags.Instance

      Dim myObjInstance As [Object] = myDomain.CreateInstanceAndUnwrap(executableNameNoExe, executableNameNoExe, False, bFlags, Nothing, Nothing, Nothing, Nothing, Nothing)

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

      myFCType.InvokeMember("CountLocalFiles", BindingFlags.InvokeMethod, Nothing, myObjInstance, New Object() {})
   End Sub 'Main
End Class 'ADDyno 


for the ability to access the location of the assembly. Associated enumeration: FileIOPermissionAccess.PathDiscovery


for the ability to read the file containing the assembly manifest. Associated enumeration: FileIOPermissionAccess.Read


for the ability to access the location of the assembly if the assembly is not local.


for the ability to call unmanaged code when creating an instance of a delegate. Associated enumeration: SecurityPermissionFlag.UnmanagedCode


for the ability to invoke operations on all type members. Associated enumeration: ReflectionPermissionFlag.MemberAccess

.NET Framework
Available since 1.1
Return to top