-3

I have this object set:

Object A
Object AA: A
Object BB: A
Object CC: A

how do i create an object of type AA Given a string variable with "AA" in it? I've been looking at the Activator stuff but can't quite figure it out.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
Charles
  • 315
  • 2
  • 9

1 Answers1

6

You need to get the Type instance for AA, then pass it to Activator.CreateInstance.

Type myType = typeof(SomeTypeInProject).Assembly.GetType(typeName);

object instance = Activator.CreateInstance(myType);
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Or `Assembly.GetExecutingAssembly()` for the assembly that the line of code appears within (avoiding the need to specify a type). (Assuming the `AA`, `BB` and `CC` are in the same assembly as the one that's doing the instantiation.) – Paul Ruane Sep 22 '11 at 16:46
  • so in my example to create an object of class BB given the string "BB": Type myType = typeof(A).Assembly.GetType("BB"); - is that right? – Charles Sep 22 '11 at 16:59
  • @Charles: Yes (assuming that they're in the same assembly) – SLaks Sep 22 '11 at 17:18