How to call a method by name?

B

bz

Hi,

I have the following situation:
a class can be loaded dynamically, and an object can be created from
it (the class implements an interface I know).
The class can have one or several methods which are not defined by the
interface. I don't know their name, but I could know their signature
(for example such method receive a parameter of type UserProfile and
returns bool)
Also, my interface have a method that returns the name (as string) of
such method
For example I can have a code like this

string authMethod = myobject.GetAuthenticationMethod();

now I want to be able to call that method, with a code like this

UserProfile upf = new UserProfile(userID);
bool retValue = CallByName(myobject, authMethod, upf);

How can I do this?

Thanks
 
M

Mike {0A6FF490-CF84-4d78-BD85-FF011A0C310C}

What does your GetAuthenticationMethod() look like?

And what do you mean by "loading a class dynamically"? Do you mean
you're dynamically loading a DLL? Or you're *instantiating* an object
that you don't necessarily know all about at compile time... other
than it implements a known interface?
 
B

bz

Hi,
What does your GetAuthenticationMethod() look like?

myobject implements an interface, which has a method

public string GetAuthenticationMethod()

and it returns the name of a method, like Login

Where Login is defined as

public void bool Login(UserProfile u)
And what do you mean by "loading a class dynamically"?  Do you mean
you're dynamically loading a DLL?  Or you're *instantiating* an object
that you don't necessarily know all about at compile time... other
than it implements a known interface?

Actually both. The idea is to implement a decoupled interface between
a front end which I implement and a back-end that is already developed
by someone else, and to be able to configure such "hooks", configured
into app.config / web.config, so the frontend can dynamically, at
runtime, resolve and load the backend components and "connect" to them

Do you have any idea about how to implement this?

Thanks
 
M

Mike {0A6FF490-CF84-4d78-BD85-FF011A0C310C}

Yes.

I think you're recreating the wheel by trying to call a method based
on its string name. You're adding a whole bunch of extra work both
for yourself as the class designer and for the users of your class
that would have to dereference the method string name and hunt down
the actual method.

When you say "hooks", I think "events" or "delegates". When you say
"my interface", I'm assuming that the code you're loading implements
YOUR interface? Which means you have control over the interface. If
that's the case, then I'd design the interface to have all of the
methods you need. Is there any reason why this wouldn't work?
 

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