AppDomain.CreateInstanceAndUnwrap Method

Definition

Creates a new instance of a specified type.

Overloads

CreateInstanceAndUnwrap(String, String)

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.

CreateInstanceAndUnwrap(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.

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

Creates a new instance of the specified type defined in the specified assembly, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes.

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)
Obsolete.

Creates a new instance of the specified type. Parameters specify the name of the type, and how it is found and created.

CreateInstanceAndUnwrap(String, String)

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type.

C#
public object? CreateInstanceAndUnwrap(string assemblyName, string typeName);
C#
public object CreateInstanceAndUnwrap(string assemblyName, string typeName);

Parameters

assemblyName
String

The display name of the assembly. See FullName.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

Returns

An instance of the object specified by typeName.

Exceptions

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 operation is attempted on an unloaded application domain.

assemblyName is not a valid assembly for the currently loaded runtime.

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

Examples

The following code example shows the simplest way to execute code in another application domain. The example defines a class named Worker that inherits from MarshalByRefObject. The Worker class defines a method that displays the name of the application domain in which it is executing. The example creates instances of Worker in the default application domain and in a new application domain.

Note

The assembly that contains Worker must be loaded into both application domains, but it can load other assemblies that exist only in the new application domain.

C#
using System;
using System.Reflection;

public class CreateInstanceWorker : MarshalByRefObject
{
    public void PrintDomain()
    {
        Console.WriteLine("Object is executing in AppDomain \"{0}\"",
            AppDomain.CurrentDomain.FriendlyName);
    }
}

class CreateInstanceAndUnwrapSourceSnippet
{
    public static void Main()
    {
        // Create an ordinary instance in the current AppDomain
        CreateInstanceWorker localWorker = new CreateInstanceWorker();
        localWorker.PrintDomain();

        // Create a new application domain, create an instance
        // of Worker in the application domain, and execute code
        // there.
        AppDomain ad = AppDomain.CreateDomain("New domain");
        CreateInstanceWorker remoteWorker = (CreateInstanceWorker) ad.CreateInstanceAndUnwrap(
            typeof(CreateInstanceWorker).Assembly.FullName,
            "Worker");
        remoteWorker.PrintDomain();
    }
}

/* This code produces output similar to the following:

Object is executing in AppDomain "source.exe"
Object is executing in AppDomain "New domain"
 */

Remarks

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

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

Note

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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

CreateInstanceAndUnwrap(String, String, Object[])

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

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#
public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, object?[]? activationAttributes);
C#
public object CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes);

Parameters

assemblyName
String

The display name of the assembly. See FullName.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

activationAttributes
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.

Returns

An instance of the object specified by typeName.

Exceptions

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 for the currently loaded runtime.

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

Examples

C#
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,
                        AssemblyBuilderAccess.RunAndSave);
    Console.WriteLine("-- Dynamic Assembly instantiated.");

    ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(executableNameNoExe,
                                      executableName);

    TypeBuilder myTypeBuilder = myModBuilder.DefineType(executableNameNoExe,
                        TypeAttributes.Public,
                        typeof(MarshalByRefObject));

    MethodBuilder myFCMethod = myTypeBuilder.DefineMethod("CountLocalFiles",
                        MethodAttributes.Public |
                        MethodAttributes.Static,
                        null,
                        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.Ldc_I4_0);
    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.
    myFCIL.MarkLabel(topOfForEachLabel);
    
        // 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.Ldelem_Ref);
    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.Ldc_I4_1);
    myFCIL.Emit(OpCodes.Add);
    myFCIL.Emit(OpCodes.Stloc_S, v1);

    // Determine if end of file list array has been reached.
    myFCIL.MarkLabel(evalForEachLabel);
    myFCIL.Emit(OpCodes.Ldloc_S, v1);
    myFCIL.Emit(OpCodes.Ldloc_S, v3);
    myFCIL.Emit(OpCodes.Ldlen);
    myFCIL.Emit(OpCodes.Conv_I4);
    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);

    myFCIL.Emit(OpCodes.Ret);

    Type myType = myTypeBuilder.CreateType();

    myAsmBuilder.SetEntryPoint(myFCMethod);
    myAsmBuilder.Save(executableName);		
    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";
    Console.WriteLine("---");

    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}'...",
                    executableNameNoExe);

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

    Console.WriteLine("---");
    Type myFCType = CreateADynamicAssembly(ref curDomain,
                     executableNameNoExe);

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

    BindingFlags bFlags = (BindingFlags.Public | BindingFlags.CreateInstance |
                   BindingFlags.Instance);

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

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

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

Remarks

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

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

Note

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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

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

Source:
AppDomain.cs
Source:
AppDomain.cs
Source:
AppDomain.cs

Creates a new instance of the specified type defined in the specified assembly, specifying whether the case of the type name is ignored; the binding attributes and the binder that are used to select the type to be created; the arguments of the constructor; the culture; and the activation attributes.

C#
public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes);
C#
public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);

Parameters

assemblyName
String

The display name of the assembly. See FullName.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean

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

bindingAttr
BindingFlags

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
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
Object[]

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 parameterless constructor is preferred, args must be an empty array or null.

culture
CultureInfo

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

activationAttributes
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.

Returns

An instance of the object specified by typeName.

Exceptions

assemblyName or typeName is null.

No matching 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 for the currently loaded runtime.

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

Examples

The following sample demonstrates the use of the ignoreCase parameter.

C#
using System;
using System.Reflection;

class IgnoreCaseSnippet {

   static void Main() {
      InstantiateINT32(false);     // Failed!
      InstantiateINT32(true);      // OK!
   }

   static void InstantiateINT32(bool ignoreCase) {
      try {
         AppDomain currentDomain = AppDomain.CurrentDomain;
         object instance = currentDomain.CreateInstanceAndUnwrap(
            "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
            "SYSTEM.INT32",
            ignoreCase,
            BindingFlags.Default,
            null,
            null,
            null,
            null,
            null
         );
         Console.WriteLine(instance.GetType());
      } catch (TypeLoadException e) {
         Console.WriteLine(e.Message);
      }
   }
}

Remarks

This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap.

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

Note

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.

See also

Applies to

.NET 9 and other versions
Product Versions
.NET Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

CreateInstanceAndUnwrap(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

Caution

Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Creates a new instance of the specified type. Parameters specify the name of the type, and how it is found and created.

C#
public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
C#
[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceAndUnwrap which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public object CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);

Parameters

assemblyName
String

The display name of the assembly. See FullName.

typeName
String

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the FullName property.

ignoreCase
Boolean

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

bindingAttr
BindingFlags

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
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
Object[]

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 parameterless constructor is preferred, args must be an empty array or null.

culture
CultureInfo

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

activationAttributes
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.

securityAttributes
Evidence

Information used to authorize creation of typeName.

Returns

An instance of the object specified by typeName.

Attributes

Exceptions

assemblyName or typeName is null.

No matching 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 for the currently loaded runtime.

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

Examples

The following sample demonstrates the use of the ignoreCase parameter.

C#
using System;
using System.Reflection;

class IgnoreCaseSnippet {

   static void Main() {
      InstantiateINT32(false);     // Failed!
      InstantiateINT32(true);      // OK!
   }

   static void InstantiateINT32(bool ignoreCase) {
      try {
         AppDomain currentDomain = AppDomain.CurrentDomain;
         object instance = currentDomain.CreateInstanceAndUnwrap(
            "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
            "SYSTEM.INT32",
            ignoreCase,
            BindingFlags.Default,
            null,
            null,
            null,
            null,
            null
         );
         Console.WriteLine(instance.GetType());
      } catch (TypeLoadException e) {
         Console.WriteLine(e.Message);
      }
   }
}

Remarks

This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap.

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

Note

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.

See also

Applies to

.NET Framework 4.8.1 and other versions
Product Versions (Obsolete)
.NET Framework 1.1, 2.0, 3.0, 3.5 (4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1)