CodeBlanks Logo Icon CodeBlanks

Activator.CreateInstance

C# course · Advanced · Lesson 45/83

Learn dynamic instantiation with Activator.CreateInstance.

Activator.CreateInstance

Activator.CreateInstance(typeof(T)) instantiates a type at runtime. It returns object; the caller must provide type safety. DI containers, serializers and plugin systems create instances this way.

For parameterized constructors use Activator.CreateInstance(typeof(T), arg1, arg2); the matching constructor is called. When the type is only known at runtime (e.g. from a config file), Activator replaces new.

Parameterized constructors

The call Activator.CreateInstance(typeof(T), 5, "text") finds the constructor whose signature matches and invokes it. The argument count, order and types must match; otherwise a MissingMethodException is thrown.

The result returns as object?; cast to the real type with as or a cast. DI containers use this to resolve dependencies; e.g. Activator.CreateInstance(typeof(MyService), logger).

Exercise Create an instance dynamically and print the type name

Create an instance dynamically with object obj = Activator.CreateInstance(typeof(Sample));. Print obj.GetType().Name with Console.WriteLine.

Show example solution
Create the instance with object obj = Activator.CreateInstance(typeof(Sample));. Print the type name with Console.WriteLine(obj.GetType().Name);.
Example solution:
using System;

class Sample
{
    public string Name { get; set; } = "Test";
}

class Program
{
    static void Main()
    {
        object obj = Activator.CreateInstance(typeof(Sample));
        Console.WriteLine(obj.GetType().Name);
    }
}

Test yourself

  1. Match the method to its purpose

    Activator.CreateInstance
    Creates an instance
    typeof(T)
    Gives a Type object
    GetType()
    Runtime type
    GetMethods()
    Method list
  2. Complete the CreateInstance call

    object obj = Activator.____(typeof(Sample));
    Show answer
    object obj = Activator.CreateInstance(typeof(Sample));
  3. What does Activator.CreateInstance return?

    • An object instance
    • A Type object
    • A MethodInfo
    • null
    Show answer

    An object instance — Correct. Activator.CreateInstance returns an object instance.

All lessons in Advanced