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?
You can get a
Typefrom astringusingType.GetType.Once you’ve got a
Typeobject, you can callActivator.CreateInstanceto instantiate it, or callType.GetConstructors, choose an appropriate constructor and then invoke it.Two “gotchas” about
Type.GetType, by the way:mscorlib, you need to specify the assembly name as well with version information if it’s strongly namedIf you have a reference to the assembly in question, then
Assembly.GetTypecan be a simpler approach – you still need to include the namespace though.