runtime creation of an object

  • Thread starter Thread starter Daniel P.
  • Start date Start date
D

Daniel P.

class MyClass1 : MyBase
class MyClass2 : MyBase

Instead of using

MyBase myB1 = new MyClass1();
MyBase myB2 = new MyClass2();

I need to create

MyBase myB1 =

using reflection, I can pass at run-time
Type t = Type.GetType( "MyClass1" );

Thanks!
 
Daniel,

Once you have the type, t, you can do this:

object o = Activator.CreateInstance(t);

However, you will still need to use reflection to call the
methods/properties on the objects. You should have a base class or
interface defined that you can cast it to, if you want to use objects of
multiple types that implement some sort of contract.

Hope this helps.
 
Yes, thanks! I have the base class. All the classes derive from the same
base class.

Nicholas Paldino said:
Daniel,

Once you have the type, t, you can do this:

object o = Activator.CreateInstance(t);

However, you will still need to use reflection to call the
methods/properties on the objects. You should have a base class or
interface defined that you can cast it to, if you want to use objects of
multiple types that implement some sort of contract.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Daniel P. said:
class MyClass1 : MyBase
class MyClass2 : MyBase

Instead of using

MyBase myB1 = new MyClass1();
MyBase myB2 = new MyClass2();

I need to create

MyBase myB1 =

using reflection, I can pass at run-time
Type t = Type.GetType( "MyClass1" );

Thanks!
 
Back
Top