What if your program could build exactly what it needs, exactly when it needs it, all by itself?
Creating instances dynamically in C Sharp (C#) - Why You Should Know This
Imagine you have many different types of objects to create in your program, but you don't know which ones until the program runs. You try to write code that creates each object by hand, one by one.
This manual way is slow and messy. You must write a lot of repeated code, and if you add new types, you have to change your code again and again. It's easy to make mistakes and hard to keep track.
Creating instances dynamically lets your program decide at runtime which object to make. You write flexible code that can create any object type without changing the code each time. This saves time and reduces errors.
if(type == "Car") { var obj = new Car(); } else if(type == "Bike") { var obj = new Bike(); }
var obj = Activator.CreateInstance(Type.GetType(typeName));
This lets your program adapt and create objects on the fly, making it powerful and easy to extend.
Think of a game where players can choose different characters. Instead of coding each character creation separately, the game creates the chosen character dynamically when the player picks it.
Manual object creation is repetitive and error-prone.
Dynamic creation makes code flexible and easier to maintain.
It allows programs to adapt and grow without rewriting code.
Practice
Activator.CreateInstance(typeof(MyClass)) do in C#?Solution
Step 1: Understand Activator.CreateInstance usage
Activator.CreateInstanceis used to create objects dynamically when the type is known only at runtime.Step 2: Analyze the given code
The codeActivator.CreateInstance(typeof(MyClass))creates a new instance ofMyClassusing its default constructor.Final Answer:
Creates a new instance of the class MyClass at runtime. -> Option AQuick Check:
Activator.CreateInstance creates objects dynamically [OK]
- Thinking it deletes or modifies existing objects
- Confusing it with type checking or conversion
- Assuming it calls any constructor without matching parameters
Person dynamically using Activator.CreateInstance?Solution
Step 1: Recall correct Activator.CreateInstance syntax
The methodActivator.CreateInstancetakes aTypeobject as parameter, e.g.,typeof(Person).Step 2: Evaluate each option
var obj = Activator.CreateInstance<Person>(typeof(Person)); uses generic syntax incorrectly by passing a Type argument. var obj = new Activator.CreateInstance(typeof(Person)); tries to usenewwith a method call, which is wrong. var obj = Activator.CreateInstance(typeof(Person)); correctly callsActivator.CreateInstance(typeof(Person)). var obj = Person.CreateInstance(); calls a non-existent method.Final Answer:
var obj = Activator.CreateInstance(typeof(Person)); -> Option AQuick Check:
Use typeof(Type) inside Activator.CreateInstance [OK]
- Using new keyword with Activator.CreateInstance
- Trying to call generic version incorrectly
- Calling non-existent CreateInstance on the class
class Animal { public string Name; public Animal() { Name = "Dog"; } }
var obj = Activator.CreateInstance(typeof(Animal));
Console.WriteLine(((Animal)obj).Name);Solution
Step 1: Understand the class and constructor
The classAnimalhas a default constructor that setsNameto "Dog".Step 2: Analyze Activator.CreateInstance and output
Activator.CreateInstance(typeof(Animal))creates a newAnimalobject, calling the default constructor. SoNameis "Dog". TheConsole.WriteLineprints this value.Final Answer:
Dog -> Option DQuick Check:
Default constructor sets Name to Dog [OK]
- Assuming Name is null because of dynamic creation
- Thinking output is class name string
- Expecting compile or runtime error
class Car { public int Speed; public Car(int speed) { Speed = speed; } }
var obj = Activator.CreateInstance(typeof(Car));Solution
Step 1: Check constructors in Car class
The classCarhas only a constructor with an int parameter. No default (parameterless) constructor exists.Step 2: Understand Activator.CreateInstance behavior
Activator.CreateInstance(typeof(Car))tries to call the default constructor. Since none exists, it throws a runtime exception.Final Answer:
Missing parameterless constructor causes runtime exception. -> Option BQuick Check:
Activator needs parameterless constructor unless parameters passed [OK]
- Assuming it creates instance without matching constructor
- Thinking it's a syntax error
- Believing fields prevent instance creation
class Book { public string Title; public Book(string title) { Title = title; } }Solution
Step 1: Understand how to pass parameters with Activator.CreateInstance
To call a constructor with parameters dynamically, pass them as additional arguments after the type.Step 2: Evaluate options
var obj = Activator.CreateInstance<Book>(typeof(Book)); uses invalid generic syntax by passing a Type argument. var obj = new Book("C# Guide"); uses normal instantiation, not dynamic. var obj = Activator.CreateInstance(typeof(Book), "C# Guide"); correctly passes the string parameter to the constructor. var obj = Activator.CreateInstance(typeof(Book)); obj.Title = "C# Guide"; creates default instance (which fails) and sets property manually, but no default constructor exists.Final Answer:
var obj = Activator.CreateInstance(typeof(Book), "C# Guide"); -> Option CQuick Check:
Pass constructor args after type in Activator.CreateInstance [OK]
- Using generic syntax incorrectly
- Trying to set properties after creation without default constructor
- Confusing normal new with dynamic creation
Ready to prove it?
Pass the test and this pattern moves unknown
