0
0
C Sharp (C#)programming~5 mins

Creating instances dynamically in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Sometimes, you want to create objects while the program is running, not just when you write the code. This helps make your program flexible and able to handle different situations.

When you want to create objects based on user input or data from a file.
When you don't know in advance which class you need to create.
When you want to reduce repeated code by creating objects in a general way.
When building plugins or modules that load classes dynamically.
When you want to create many objects without writing each one manually.
Syntax
C Sharp (C#)
var instance = Activator.CreateInstance(typeof(ClassName));

// Or with generics:
var instance = Activator.CreateInstance<ClassName>();

Activator.CreateInstance is a built-in method to create objects when you only have the type at runtime.

You can also pass constructor arguments as extra parameters to CreateInstance.

Examples
This creates a Person object dynamically and prints the default name.
C Sharp (C#)
class Person {
    public string Name;
    public Person() {
        Name = "Unknown";
    }
}

var person = (Person)Activator.CreateInstance(typeof(Person));
Console.WriteLine(person.Name);
This creates a Car object dynamically and passes "Tesla" to the constructor.
C Sharp (C#)
class Car {
    public string Model;
    public Car(string model) {
        Model = model;
    }
}

var car = (Car)Activator.CreateInstance(typeof(Car), "Tesla");
Console.WriteLine(car.Model);
This creates a generic list of integers dynamically and prints its type name.
C Sharp (C#)
var list = (System.Collections.Generic.List<int>)Activator.CreateInstance(typeof(System.Collections.Generic.List<int>));
Console.WriteLine(list.GetType().Name);
Sample Program

This program creates an Animal object dynamically using its type and prints the default name.

C Sharp (C#)
using System;

class Animal {
    public string Name;
    public Animal() {
        Name = "NoName";
    }
}

class Program {
    static void Main() {
        Type type = typeof(Animal);
        var animal = (Animal)Activator.CreateInstance(type);
        Console.WriteLine($"Animal name: {animal.Name}");
    }
}
OutputSuccess
Important Notes

Make sure the class has a public constructor that matches the parameters you pass.

If the class does not have a parameterless constructor, you must provide arguments to CreateInstance.

Using dynamic creation can be slower than normal object creation, so use it only when needed.

Summary

You can create objects dynamically using Activator.CreateInstance.

This helps when you don't know the exact class at compile time.

Remember to match constructors and handle exceptions if creation fails.