Export (0) Print
Expand All

Activator.CreateInstance Method (String, String)

Creates an instance of the type whose name is specified, using the named assembly and default constructor.

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

public static ObjectHandle CreateInstance(
	string assemblyName,
	string typeName
)

Parameters

assemblyName
Type: System.String

The name of the assembly where the type named typeName is sought. For more information, see the Remarks section. If assemblyName is null, the executing assembly is searched.

typeName
Type: System.String

The fully qualified name of the preferred type.

Return Value

Type: System.Runtime.Remoting.ObjectHandle
A handle that must be unwrapped to access the newly created instance.

ExceptionCondition
ArgumentNullException

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.

MemberAccessException

You cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

TargetInvocationException

The constructor, which was invoked through reflection, threw an exception.

InvalidComObjectException

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

NotSupportedException

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

BadImageFormatException

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

FileLoadException

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

-or-

The assembly name or code base is invalid.

Use ObjectHandle.Unwrap to unwrap the return value.

assemblyName can be either of the following:

  • The simple name of an assembly, without its path or file extension. For example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.

  • The full name of a signed assembly, which consists of its simple name, version, culture, and public key token; for example, "TypeExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=181869f2f7435b51".

For more information on how the common language runtime identifies and loads assemblies, see How the Runtime Locates Assemblies. For information on using the application configuration file to define assembly locations, see Specifying an Assembly's Location. If assemblyName is found, it is loaded in the default context.

NoteNote

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

The following example defines a class named Person in an assembly named PersonInfo. Note that the Person class has two constructors, one of which is parameterless.

using System;

public class Person
{
   private string _name;

   public Person()
   { }

   public Person(string name)
   {
      this._name = name;
   }

   public string Name
   { get { return this._name; }
     set { this._name = value; } }

   public override string ToString()
   {
      return this._name;
   }
}

The following example calls the CreateInstance(String, String) method to instantiate the Person class. It requires a reference to PersonInfo.dll to be added to the project. Because the CreateInstance(String, String) method calls the Person class default constructor, the example assigns a value to its Name property.

using System;
using System.Runtime.Remoting;

public class Example
{
   public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Person p = (Person) handle.Unwrap();
      p.Name = "Samuel";
      Console.WriteLine(p);
   }
}
// The example displays the following output: 
//        Samuel

However, CreateInstance is frequently called to instantiate a type that crosses machine boundaries or that is not known at design time. In this case, you cannot include a reference to the assembly in the project and cannot make early-bound calls to the type's members. To work around this limitation, the following example uses the CreateInstance method along with reflection to assign a value to the Person object's Name property and to display its value.

using System;
using System.Reflection;
using System.Runtime.Remoting;

public class Example
{
   public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Object p = handle.Unwrap();
      Type t = p.GetType();
      PropertyInfo prop = t.GetProperty("Name");
      if (prop != null)
         prop.SetValue(p, "Samuel");

      MethodInfo method = t.GetMethod("ToString");
      Object retVal = method.Invoke(p, null); 
      if (retVal != null)
         Console.WriteLine(retVal);
   }
}
// The example displays the following output: 
//        Samuel

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Show:
© 2014 Microsoft