Activator Class (System)

Switch View :
ScriptFree
.NET Framework Class Library
Activator Class

Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. This class cannot be inherited.

Inheritance Hierarchy

System.Object
  System.Activator

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

Visual Basic
<ComVisibleAttribute(True)> _
<ClassInterfaceAttribute(ClassInterfaceType.None)> _
Public NotInheritable Class Activator _
	Implements _Activator
C#
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType.None)]
public sealed class Activator : _Activator
Visual C++
[ComVisibleAttribute(true)]
[ClassInterfaceAttribute(ClassInterfaceType::None)]
public ref class Activator sealed : _Activator
F#
[<Sealed>]
[<ComVisibleAttribute(true)>]
[<ClassInterfaceAttribute(ClassInterfaceType.None)>]
type Activator =  
    class
        interface _Activator
    end

The Activator type exposes the following members.

Methods

  Name Description
Public method Static member CreateComInstanceFrom(String, String) Creates an instance of the COM object whose name is specified, using the named assembly file and the constructor that best matches the specified parameters.
Public method Static member CreateComInstanceFrom(String, String, Byte[], AssemblyHashAlgorithm) Creates an instance of the COM object whose name is specified, using the named assembly file and the default constructor.
Public method Static member CreateInstance(ActivationContext) Creates an instance of the type designated by the specified ActivationContext object.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library CreateInstance(Type) Creates an instance of the specified type using that type's default constructor.
Public method Static member CreateInstance(ActivationContext, String[]) Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data.
Public method Static member CreateInstance(String, String) Creates an instance of the type whose name is specified, using the named assembly and default constructor.
Public method Static member CreateInstance(Type, Boolean) Creates an instance of the specified type using that type's default constructor.
Public method Static member Supported by Portable Class Library CreateInstance(Type, Object[]) Creates an instance of the specified type using the constructor that best matches the specified parameters.
Public method Static member CreateInstance(AppDomain, String, String) Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and default constructor.
Public method Static member CreateInstance(String, String, Object[]) Creates an instance of the type whose name is specified, using the named assembly and default constructor.
Public method Static member CreateInstance(Type, Object[], Object[]) Creates an instance of the specified type using the constructor that best matches the specified parameters.
Public method Static member CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo) Creates an instance of the specified type using the constructor that best matches the specified parameters.
Public method Static member CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[]) Creates an instance of the specified type using the constructor that best matches the specified parameters.
Public method Static member CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.
Public method Static member CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.
Public method Static member CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.
Public method Static member CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.
Public method Static member Supported by the XNA Framework Supported by Portable Class Library CreateInstance<T>() Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor .
Public method Static member CreateInstanceFrom(String, String) Creates an instance of the type whose name is specified, using the named assembly file and default constructor.
Public method Static member CreateInstanceFrom(AppDomain, String, String) Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly file and default constructor.
Public method Static member CreateInstanceFrom(String, String, Object[]) Creates an instance of the type whose name is specified, using the named assembly file and default constructor.
Public method Static member CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) Creates an instance of the type whose name is specified, using the named assembly file and the constructor that best matches the specified parameters.
Public method Static member CreateInstanceFrom(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly file and the constructor that best matches the specified parameters.
Public method Static member CreateInstanceFrom(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates an instance of the type whose name is specified, using the named assembly file and the constructor that best matches the specified parameters.
Public method Static member CreateInstanceFrom(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence) Obsolete. Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly file and the constructor that best matches the specified parameters.
Public method Supported by the XNA Framework Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method Static member GetObject(Type, String) Creates a proxy for the well-known object indicated by the specified type and URL.
Public method Static member GetObject(Type, String, Object) Creates a proxy for the well-known object indicated by the specified type, URL, and channel data.
Public method Supported by the XNA Framework GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method Supported by the XNA Framework MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Supported by the XNA Framework ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Explicit Interface Implementations

  Name Description
Explicit interface implemetation Private method _Activator.GetIDsOfNames Maps a set of names to a corresponding set of dispatch identifiers.
Explicit interface implemetation Private method _Activator.GetTypeInfo Retrieves the type information for an object, which can then be used to get the type information for an interface.
Explicit interface implemetation Private method _Activator.GetTypeInfoCount Retrieves the number of type information interfaces that an object provides (either 0 or 1).
Explicit interface implemetation Private method _Activator.Invoke Provides access to properties and methods exposed by an object.
Top
Remarks

The CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If no arguments are specified, the constructor that takes no parameters, that is, the default constructor, is invoked.

You must have sufficient permission to search for and call a constructor; otherwise, an exception is thrown. By default, only public constructors are considered during the search for a constructor. If no constructor or default constructor can be found, an exception is thrown.

A binder parameter specifies an object that searches an assembly for a suitable constructor. You can specify your own binder and search criteria. If no binder is specified, a default binder is used. For more information, see the System.Reflection.Binder and System.Reflection.BindingFlags classes.

An evidence parameter affects the security policy and permissions for the constructor. For more information, see the System.Security.Policy.Evidence class.

An instance of a type can be created at a local or remote site. If the type is created remotely, an activation attribute parameter specifies the URI of the remote site. The call to create the instance might pass through intermediary sites before it reaches the remote site. Other activation attributes can modify the environment, or context, in which the call operates at the remote and intermediary sites.

If the instance is created locally, a reference to that object is returned. If the instance is created remotely, a reference to a proxy is returned. The remote object is manipulated through the proxy as if it were a local object.

The GetObject method creates a proxy to a currently running remote object, server-activated well-known object, or XML Web service. You can specify the connection medium, that is, the channel. For more information, see the System.Runtime.Remoting.Channels.ChannelServices class.

Assemblies contain type definitions. The CreateInstance method creates an instance of a type from a currently running assembly. The CreateInstanceFrom method creates an instance from a file that contains an assembly. The CreateComInstanceFrom method creates an instance of a COM object from a file that contains an assembly.

Examples

The following example shows how to use the Activator class to dynamically construct objects at run time.

Visual Basic

Imports System.Reflection
Imports System.Text

Module Module1
    Sub Main()
        ' Create an instance of the StringBuilder type using 
        ' Activator.CreateInstance.
        Dim o As Object = Activator.CreateInstance(GetType(StringBuilder))

        ' Append a string into the StringBuilder object and display the 
        ' StringBuilder.
        Dim sb As StringBuilder = CType(o, StringBuilder)
        sb.Append("Hello, there.")
        Console.WriteLine(sb)

        ' Create an instance of the SomeType class that is defined in this assembly.
        Dim oh As System.Runtime.Remoting.ObjectHandle = _
            Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, _
                                         GetType(SomeType).FullName)

        ' Call an instance method defined by the SomeType type using this object.
        Dim st As SomeType = CType(oh.Unwrap(), SomeType)

        st.DoSomething(5)
    End Sub

    Class SomeType
        Public Sub DoSomething(ByVal x As Int32)
            Console.WriteLine("100 / {0} = {1}", x, 100 \ x)
        End Sub
    End Class
End Module

' This code produces the following output:
' 
' Hello, there.
' 100 / 5 = 20


C#

using System;
using System.Reflection;
using System.Text;

public class SomeType
{
    public void DoSomething(int x)
    {
        Console.WriteLine("100 / {0} = {1}", x, 100 / x);
    }
}

public class Example
{
    static void Main()
    {
        // Create an instance of the StringBuilder type using 
        // Activator.CreateInstance.
        Object o = Activator.CreateInstance(typeof(StringBuilder));

        // Append a string into the StringBuilder object and display the 
        // StringBuilder.
        StringBuilder sb = (StringBuilder) o;
        sb.Append("Hello, there.");
        Console.WriteLine(sb);

        // Create an instance of the SomeType class that is defined in this 
        // assembly.
        System.Runtime.Remoting.ObjectHandle oh = 
            Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, 
                                         typeof(SomeType).FullName);

        // Call an instance method defined by the SomeType type using this object.
        SomeType st = (SomeType) oh.Unwrap();

        st.DoSomething(5);
    }
}

/* This code produces the following output:

Hello, there.
100 / 5 = 20
 */


Visual C++

using namespace System;
using namespace System::Reflection;
using namespace System::Text;

public ref class SomeType
{
public:
    void DoSomething(int x)
    {
        Console::WriteLine("100 / {0} = {1}", x, 100 / x);
    }
};

void main()
{
    // Create an instance of the StringBuilder type using 
    // Activator.CreateInstance.
    Object^ o = Activator::CreateInstance(StringBuilder::typeid);

    // Append a string into the StringBuilder object and display the 
    // StringBuilder.
    StringBuilder^ sb = (StringBuilder^) o;
    sb->Append("Hello, there.");
    Console::WriteLine(sb);

    // Create an instance of the SomeType class that is defined in this 
    // assembly.
    System::Runtime::Remoting::ObjectHandle^ oh = 
        Activator::CreateInstanceFrom(Assembly::GetEntryAssembly()->CodeBase, 
                                      SomeType::typeid->FullName);

    // Call an instance method defined by the SomeType type using this object.
    SomeType^ st = (SomeType^) oh->Unwrap();

    st->DoSomething(5);
};

/* This code produces the following output:

Hello, there.
100 / 5 = 20
 */


Version Information

.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

Portable Class Library

Supported in: Portable Class Library
Platforms

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.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Other Resources

Community Content

Morten Wennevik
Additional example

This class is useful when you need to load an assembly at runtime and create an object from that assembly, for instance using a plugin architecture. In this sample you can also use Assembly.CreateInstance.

  void LoadPlugins(string pluginFolder)
{
    foreach(var file in Directory.GetFiles(pluginFolder, "*Plugin.dll"))
    {
        var pluginAssembly = Assembly.LoadFrom(file);
        var assemblyTypes = pluginAssembly.GetTypes();
        foreach (var type in assemblyTypes)
        {                    
            if (type.GetInterface("IPlugin") != null)
            {
                var plugin1 = pluginAssembly.CreateInstance(type.FullName);
                var plugin2 = Activator.CreateInstance(type) as IPlugin;                        
            }
        }
    }
}