📖 Scenario: Imagine you are building a simple program that creates different types of vehicles based on user input. Each vehicle has a name and a speed. You want to create these vehicle objects dynamically using their class names.
🎯 Goal: Build a C# program that dynamically creates instances of vehicle classes using their names as strings, and then displays their details.
📋 What You'll Learn
Create two classes: Car and Bike, each with a Name and Speed property.
Create a string variable called vehicleType that holds the name of the class to create.
Use Activator.CreateInstance to create an instance of the class named in vehicleType.
Set the Name and Speed properties of the created instance.
Print the Name and Speed of the created vehicle.
💡 Why This Matters
🌍 Real World
Creating instances dynamically is useful when you want to build flexible programs that can create objects based on user input or configuration files without hardcoding all types.
💼 Career
This skill is important for developers working on plugin systems, factories, or any software that needs to load and create objects at runtime based on names or types.
Progress0 / 4 steps
1
Create vehicle classes
Create two classes called Car and Bike. Each class should have two public properties: Name (string) and Speed (int).
C Sharp (C#)
Hint
Use public class ClassName to create classes. Use public string Name { get; set; } to create properties.
2
Set vehicle type variable
Create a string variable called vehicleType and set it to "Car".
C Sharp (C#)
Hint
Use string vehicleType = "Car"; to create the variable.
3
Create instance dynamically
Use Activator.CreateInstance with Type.GetType(vehicleType) to create an object called vehicle. Then cast it to dynamic. Set vehicle.Name to "Speedster" and vehicle.Speed to 120.
C Sharp (C#)
Hint
Use Type.GetType(vehicleType) to get the type, then Activator.CreateInstance(type) to create the object. Cast to dynamic to set properties easily.
4
Print vehicle details
Write a Console.WriteLine statement to print the vehicle's Name and Speed in this format: "Vehicle: Speedster, Speed: 120".
C Sharp (C#)
Hint
Use Console.WriteLine($"Vehicle: {vehicle.Name}, Speed: {vehicle.Speed}") to print the details.
Practice
(1/5)
1. What does Activator.CreateInstance(typeof(MyClass)) do in C#?
easy
A. Creates a new instance of the class MyClass at runtime.
B. Deletes an existing instance of MyClass.
C. Checks if MyClass has a default constructor.
D. Converts MyClass to a string representation.
Solution
Step 1: Understand Activator.CreateInstance usage
Activator.CreateInstance is used to create objects dynamically when the type is known only at runtime.
Step 2: Analyze the given code
The code Activator.CreateInstance(typeof(MyClass)) creates a new instance of MyClass using its default constructor.
Final Answer:
Creates a new instance of the class MyClass at runtime. -> Option A
The method Activator.CreateInstance takes a Type object 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 use new with a method call, which is wrong. var obj = Activator.CreateInstance(typeof(Person)); correctly calls Activator.CreateInstance(typeof(Person)). var obj = Person.CreateInstance(); calls a non-existent method.
Final Answer:
var obj = Activator.CreateInstance(typeof(Person)); -> Option A
Quick Check:
Use typeof(Type) inside Activator.CreateInstance [OK]
Hint: Use typeof(Type) inside Activator.CreateInstance() [OK]
Common Mistakes:
Using new keyword with Activator.CreateInstance
Trying to call generic version incorrectly
Calling non-existent CreateInstance on the class
3. What will be the output of this code?
class Animal { public string Name; public Animal() { Name = "Dog"; } } var obj = Activator.CreateInstance(typeof(Animal)); Console.WriteLine(((Animal)obj).Name);
medium
A. null
B. Compilation error
C. Animal
D. Dog
Solution
Step 1: Understand the class and constructor
The class Animal has a default constructor that sets Name to "Dog".
Step 2: Analyze Activator.CreateInstance and output
Activator.CreateInstance(typeof(Animal)) creates a new Animal object, calling the default constructor. So Name is "Dog". The Console.WriteLine prints this value.
Final Answer:
Dog -> Option D
Quick Check:
Default constructor sets Name to Dog [OK]
Hint: Activator calls default constructor, so fields are initialized [OK]
Common Mistakes:
Assuming Name is null because of dynamic creation
Thinking output is class name string
Expecting compile or runtime error
4. Identify the error in this code snippet:
class Car { public int Speed; public Car(int speed) { Speed = speed; } } var obj = Activator.CreateInstance(typeof(Car));
medium
A. No error, instance created successfully.
B. Missing parameterless constructor causes runtime exception.
C. Syntax error in Activator.CreateInstance call.
D. Cannot create instance of class with fields.
Solution
Step 1: Check constructors in Car class
The class Car has only a constructor with an int parameter. No default (parameterless) constructor exists.
Hint: Activator.CreateInstance needs parameterless constructor unless parameters given [OK]
Common Mistakes:
Assuming it creates instance without matching constructor
Thinking it's a syntax error
Believing fields prevent instance creation
5. You want to create an instance of a class dynamically and pass constructor parameters. Which is the correct way to do this?
class Book { public string Title; public Book(string title) { Title = title; } }
hard
A. var obj = new Book("C# Guide");
B. var obj = Activator.CreateInstance<Book>(typeof(Book));
C. var obj = Activator.CreateInstance(typeof(Book), "C# Guide");
D. var obj = Activator.CreateInstance(typeof(Book)); obj.Title = "C# Guide";
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 C
Quick Check:
Pass constructor args after type in Activator.CreateInstance [OK]
Hint: Pass constructor arguments after type in Activator.CreateInstance [OK]
Common Mistakes:
Using generic syntax incorrectly
Trying to set properties after creation without default constructor
Confusing normal new with dynamic creation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.