Reflection Design Help

A

admin

I am trying to get reflection to work and have been spending today
trying to understand it better. I am stuck and hoping someone could
point me in the right direction (maybe a different way of doing this).

I have several different types (classes) and all have an IsValid()
function. (ie. Coke.IsValid(), Gatorade.IsValid(), etc) I am using
the below code to dynamically have the right class's IsValid() called
during my app.

// system.reflection
Assembly a = Assembly.GetExecutingAssembly();
Type t = a.GetType(typeNAME); <-- typeNAME is string with
namespace.class pulled from a DB
object obj = Activator.CreateInstance(t);
obj.IsValid(); <-- error here

I get an error that "'object' does not contain a definition for
'IsValid'" ... which I understand, but how does one call the function
when using reflection? I may need to cast it, but that would not make
this dynamic then. (unless you can dynamically cast something?)

Is there a better way to design/pattern a solution? I am interested
in learning how others design a sort of plugin model (if that's the
right wording)

Thanks for any help/ideas/tip you can share.
 
J

Jon Skeet [C# MVP]

I am trying to get reflection to work and have been spending today
trying to understand it better. I am stuck and hoping someone could
point me in the right direction (maybe a different way of doing this).

I have several different types (classes) and all have an IsValid()
function. (ie. Coke.IsValid(), Gatorade.IsValid(), etc) I am using
the below code to dynamically have the right class's IsValid() called
during my app.

// system.reflection
Assembly a = Assembly.GetExecutingAssembly();
Type t = a.GetType(typeNAME); <-- typeNAME is string with
namespace.class pulled from a DB
object obj = Activator.CreateInstance(t);
obj.IsValid(); <-- error here

I get an error that "'object' does not contain a definition for
'IsValid'" ... which I understand, but how does one call the function
when using reflection? I may need to cast it, but that would not make
this dynamic then. (unless you can dynamically cast something?)

Is there a better way to design/pattern a solution? I am interested
in learning how others design a sort of plugin model (if that's the
right wording)

A *much* better solution to this is to make all your classes implement
a common interface, eg IValidatable. Then you just need to cast to the
interface.

See http://pobox.com/~skeet/csharp/plugin.html for an example.
 

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