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.
Creating instances dynamically in 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.
Person object dynamically and prints the default name.class Person { public string Name; public Person() { Name = "Unknown"; } } var person = (Person)Activator.CreateInstance(typeof(Person)); Console.WriteLine(person.Name);
Car object dynamically and passes "Tesla" to the constructor.class Car { public string Model; public Car(string model) { Model = model; } } var car = (Car)Activator.CreateInstance(typeof(Car), "Tesla"); Console.WriteLine(car.Model);
var list = (System.Collections.Generic.List<int>)Activator.CreateInstance(typeof(System.Collections.Generic.List<int>)); Console.WriteLine(list.GetType().Name);
This program creates an Animal object dynamically using its type and prints the default name.
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}"); } }
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.
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.