Creating an object with a variable

D

DaveD

OK, this may be simple, but...

I have a 5 classes, they all bring up a form to edit a table, and
they're all derivied from a virtual class. The user is allowed to pick
a table to edit from a drop-down list that was populated from a SQL
table, this table also contains the name of the class that is used to
edit it. Can I use 1 new statment to create the correct object or do I
have to use a switch?

Thanks,
Dave
 
N

Nicholas Paldino [.NET/C# MVP]

Dave,

You could use a switch, but in reality, you will want to look at the
static GetType method on the Type class. With this, assuming you have a
fully qualified type name, you can get the type that you have stored in the
database. Then, you can pass that Type instance to the static
CreateInstance method on the Activator class, and it will return an instance
of that type.

This assumes that they all have the same constructor of course
(parameterless, or same number/type of arguments).

Hope this helps.
 
G

Greg Young

I would recommend using the factory pattern to encapsulat the logic.

You can either use a switch or you can use Activator.CreateInstance() (or
more correctly you could include the assembly and use
Assembly.CreateInstance as the assembly that the type is in may have not
been loaded yet :)

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 

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