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

Creating instances dynamically in C Sharp (C#) - Try It Yourself

Choose your learning style9 modes available
Creating instances dynamically
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

Use Console.WriteLine($"Vehicle: {vehicle.Name}, Speed: {vehicle.Speed}") to print the details.