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.