runtime creation of an object

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!
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
D

Daniel P.

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top