Passing function as an argument and executing

  • Thread starter Thread starter ray.ackley
  • Start date Start date
R

ray.ackley

I know you can do this in C++ as I remember doing it in my college days
(just a few years ago), but I'm having trouble finding reference on how
to do it with a managed language.

What I have is a wrapper function that performs a somewhat complex
enumeration of different objects that can be used to accomplish many
different tasks on each object.

I have each task seperated into it's own function because embedding all
the functions into an endless if/then/else inside the wrapper function
would be rather hard to read, and poor coding to boot.

What I'd like to do is somehow pass a reference to a single one of
these functions to the wrapper function when it is invoked, so that
when it has waded through all the enumeration logic it can then invoke
the "worker" function with proper arguments.
It this possible, and if so, how can I implement it?

Thanks,
Ray
 
What you want to do is create a delegate for this function / method.

The C# equivalent of C++ function pointers is delegates. Yes, delegates
are often used in conjunction with events, and are also used for
multicast, but you can also use simple delegates as function pointers.
 
Ray... The general solution when faced with a switch is to abstract the
action
into an interface. Then write an adapter or helper class that
implements the abstract interface and contains the state for each
object. Pass
the adapter to the caller and the caller invokes the abstract function
call. The
adapter knows its own state and invokes the appropriate action. No
switch
needed. By converting from a switch to a stateful object, you support
extensibility. You can write a new class adapter for a new class and
pass the
new adapter to the client. Now if this makes no sense I am still writing
a
chapter on dynamic class factories, but some code is up at:
http://www.geocities.com/jeff_louie/OOP/oop18.htm

Regards,
Jeff
What I'd like to do is somehow pass a reference to a single one of
these functions to the wrapper function when it is invoked, so that
when it has waded through all the enumeration logic it can then invoke
the "worker" function with proper arguments.<
 
Back
Top