tags:

views:

80

answers:

2

If one had a class such as 'Painter' and one needed the user to be able to create an instance or instances of this class @ runtime, what's the best way to go about this?

So each time a user clicks a button, we need a new painter object?

Or each time the user enters 'new painter' we need a new painter instance?

+3  A: 

I'm guessing that the gist of your question is that the class type is unknown prior to the user's input. Otherwise, if you wanted a new Painter class on each button click, you could simply handle the button click and do "var newpainter = new Painter();".

So, assuming you need to dynamically create an instance of an unknown type, you can use reflection to do this at runtime.

var newpainter =  Activator.CreateInstance(Type.GetType("Painter"), args);
womp
+5  A: 

You can get a Type from a string using Type.GetType.

Once you've got a Type object, you can call Activator.CreateInstance to instantiate it, or call Type.GetConstructors, choose an appropriate constructor and then invoke it.

Two "gotchas" about Type.GetType, by the way:

  • You have to include the namespace in the type name
  • Unless the type is in the currently executing assembly or mscorlib, you need to specify the assembly name as well with version information if it's strongly named

If you have a reference to the assembly in question, then Assembly.GetType can be a simpler approach - you still need to include the namespace though.

Jon Skeet
"version information if it's strongly typed" should have been "version information if it's strongly named"
AZ
@AZ: Thanks, fixing now.
Jon Skeet