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