Delegate limitations?

T

Tim Smith

Hi,

If I have 5-10 methods with different signatures, different content
except for the first 6 and last lines, can I use delegates to share
the 12 lines of code.

e.g.

public void method1(string p1, int p2) {
line1();
... line6();
// lines specific to method1 here
line7();
... line6();
}
public int method2(object o, myclass mc, anotherclass ac) {
line1();
... line6();
// lines specific to method2 here
line7();
... line6();
}
etc

I would like to share without making method1,method2, et al
unreadable...

thanks

Tim
 
K

Ken Kolda

Without changing the way you're doing things there's no way to "share" the
delegates -- they are tied to the signature of the function it encapsulates.
Of course, you could encapsulate your 12 lines of code into two functions
which are called from each of your method1(), method2(), etc.

Another, more OO way to do this is to abstract away the function argument
and call semantics of the "inner stuff" that is distinct to your different
methods so you can general these operations. For example, you could create
an interface such as:

interface IExecutable
{
void Execute();
}

Then create a function

public void execute(IExecutable exe)
{
line1();
...line6();
exe.Execute(); // Execute the process passed
line7();
...line12();
}

Now you only need 1 delegate to wrap this function and you only have your 12
lines of code in a single place. What's left is, for each of your 5-10
methods, you need to implement a class that performs the "inner stuff" of
the call. The class's constructor would take the arguments you were
previously passing to the individual methods, e.g.

public class Method1Impl : IExecutable
{
public Method1Impl(string p1, int p2) { ... }
public void Execute() { /* Inner code here */ }
}

Now you can reuse your execute() function (and its corresponding delegate)
for as many processes as you want, and the only code you have to write for
each is the actual implementation code for the specific process.

Ken
 
I

Ignacio Machin \( .NET/ C# MVP \)

What for?

Why not simply create two method ( or one if the 6 lines are the same &
start and end ) and you just that method(s).

Cheers,
 
T

Tim Smith

Some of those lines are a try {} catch with pre and postamble that you
could not put into a standalone method.
 

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