Open In App

Creating Instances Dynamically in C#

Last Updated : 24 Oct, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, objects are usually created using the new keyword at compile time. However, in some cases, you may not know the type of object you need to create until runtime. To handle such scenarios, C# provides mechanisms to create instances dynamically using Reflection and the Activator class.

This is particularly useful in scenarios like plugin systems, dependency injection and dynamic loading of assemblies.

Methods to Create Instances Dynamically

1. Using the Activator Class

The Activator class in the System namespace provides methods to create instances of types dynamically.

Syntax:

object instance = Activator.CreateInstance(type);

Example:

C#
using System;

class Student
{
    public string Name { get; set; }
    public void Display() => Console.WriteLine($"Student Name: {Name}");
}

class Program
{
    static void Main()
    {
        Type type = typeof(Student);
        object obj = Activator.CreateInstance(type);

        Student student = (Student)obj;
        student.Name = "Rahul";
        student.Display();
    }
}

Output
Student Name: Rahul
  • Returns object, so you must cast it to the appropriate type.
  • The class must have a public parameterless constructor.
  • Useful when the type is not known at compile time.

2. Using Activator with Parameterized Constructors

You can also pass arguments to the constructor dynamically.

C#
using System;

class Employee
{
    public string Name { get; }
    public int Id { get; }

    public Employee(string name, int id)
    {
        Name = name;
        Id = id;
    }

    public void Display() => Console.WriteLine($"{Name} - {Id}");
}

class Program
{
    static void Main()
    {
        Type type = typeof(Employee);
        object obj = Activator.CreateInstance(type, "Amit", 101);
        ((Employee)obj).Display();
    }
}

Output
Amit - 101

Activator.CreateInstance accepts constructor arguments as additional parameters, which allows dynamic instantiation with initialization.

3. Using Reflection and ConstructorInfo

Reflection can be used to get specific constructors and create instances more explicitly.

C#
using System;
using System.Reflection;

class Product
{
    public string Name { get; }
    public double Price { get; }

    public Product(string name, double price)
    {
        Name = name;
        Price = price;
    }

    public void Show() => Console.WriteLine($"{Name} - {Price}");
}

class Program
{
    static void Main()
    {
        Type type = typeof(Product);
        ConstructorInfo ctor = type.GetConstructor(new[] { typeof(string), typeof(double) });
        object instance = ctor.Invoke(new object[] { "Laptop", 55000.0 });

        ((Product)instance).Show();
    }
}

Output
Laptop - 55000
  • Offers more control than Activator.
  • Useful when a class has multiple constructors.
  • Works well for frameworks or libraries that need advanced reflection-based instantiation.

4. Using Generic Type Parameters

When type information is available as a generic parameter, you can create an instance using new() constraint.

C#
class Factory
{
    public static T CreateInstance<T>() where T : new()
    {
        return new T();
    }
}

class Car
{
    public void Drive() => Console.WriteLine("Driving Car...");
}

class Program
{
    static void Main()
    {
        Car car = Factory.CreateInstance<Car>();
        car.Drive();
    }
}
  • Compile-time type-safe.
  • Only works for types with a public parameterless constructor.
  • Does not involve reflection, so it’s faster than Activator.

5. Using Assembly to Create Instances from External DLLs

You can dynamically load an assembly and create an instance of a class defined within it.

C#
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Assembly assembly = Assembly.LoadFrom("ExternalLibrary.dll");
        Type type = assembly.GetType("ExternalLibrary.Calculator");
        object obj = Activator.CreateInstance(type);
        Console.WriteLine($"Instance created of type: {type.FullName}");
    }
}

Use Case:

  • When the type exists in an external DLL loaded at runtime.
  • Common in plugin or modular application architectures.

When to Use Dynamic Instance Creation

  • When implementing factory patterns that decide object types at runtime.
  • When using dependency injection frameworks.
  • When building plugin-based applications or reflection-heavy frameworks.
  • When types are not known at compile time but determined from configuration files or user input.

Performance Considerations

  • Reflection and Activator.CreateInstance are slower compared to normal instantiation.
  • Use them only when necessary.
  • For frequently created objects, consider caching constructor delegates for performance improvement.
Suggested Quiz
4 Questions

What is the primary use of the Activator.CreateInstance() method?

  • A

    To invoke a static method

  • B

    To load an assembly

  • C

    To create an object dynamically at runtime

  • D

    To retrieve metadata

Explanation:

Activator.CreateInstance() instantiates objects whose type may not be known until runtime.

What is the purpose of the dynamic keyword in C#?

  • A

    To enforce strict compile-time type checking

  • B

    To define value types

  • C

    To declare immutable variables

  • D

    To defer type checking until runtime

Explanation:


Which class allows adding members dynamically at runtime in C#?

  • A

    Type

  • B

    ExpandoObject

  • C

    DynamicObject

  • D

    ObjectBuilder

Explanation:


Which of the following scenarios justifies using dynamic instance creation?

  • A

    When type is known at compile time

  • B

    When frequent object creation is needed

  • C

    When implementing plugin-based architectures

  • D

    When performance is critical

Explanation:

Dynamic instance creation is suitable for modular systems where types are loaded and instantiated at runtime.

Image
Quiz Completed Successfully
Your Score :   2/4
Accuracy :  0%
Login to View Explanation
1/4 1/4 < Previous Next >

Article Tags :

Explore