Concept Flow - Creating instances dynamically
Start
Get Type info
Call Activator.CreateInstance
New object created
Use the object
End
This flow shows how a program gets type information, creates an instance dynamically, and then uses the new object.
using System; class Person { public string Name; public Person() { Name = "Unknown"; } } class Program { static void Main() { var type = typeof(Person); var obj = Activator.CreateInstance(type); Console.WriteLine(((Person)obj).Name); } }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Get type info | typeof(Person) | Person type info stored in 'type' |
| 2 | Create instance | Activator.CreateInstance(type) | New Person object created, stored in 'obj' |
| 3 | Access property | ((Person)obj).Name | "Unknown" |
| 4 | Print output | Console.WriteLine | Outputs: Unknown |
| 5 | End | No more code | Program ends |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| type | null | Person type info | Person type info | Person type info | Person type info |
| obj | null | null | Person instance | Person instance | Person instance |
| Name | N/A | N/A | N/A | "Unknown" | "Unknown" |
Creating instances dynamically in C#: - Use typeof(TypeName) to get type info. - Use Activator.CreateInstance(type) to create an object. - Cast the object to the correct type to access members. - Requires a parameterless constructor. - Useful for flexible, runtime object creation.
Activator.CreateInstance(typeof(MyClass)) do in C#?Activator.CreateInstance is used to create objects dynamically when the type is known only at runtime.Activator.CreateInstance(typeof(MyClass)) creates a new instance of MyClass using its default constructor.Person dynamically using Activator.CreateInstance?Activator.CreateInstance takes a Type object as parameter, e.g., typeof(Person).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.class Animal { public string Name; public Animal() { Name = "Dog"; } }
var obj = Activator.CreateInstance(typeof(Animal));
Console.WriteLine(((Animal)obj).Name);Animal has a default constructor that sets Name to "Dog".Activator.CreateInstance(typeof(Animal)) creates a new Animal object, calling the default constructor. So Name is "Dog". The Console.WriteLine prints this value.class Car { public int Speed; public Car(int speed) { Speed = speed; } }
var obj = Activator.CreateInstance(typeof(Car));Car has only a constructor with an int parameter. No default (parameterless) constructor exists.Activator.CreateInstance(typeof(Car)) tries to call the default constructor. Since none exists, it throws a runtime exception.class Book { public string Title; public Book(string title) { Title = title; } }Pass the test and this pattern moves unknown