How to refactor out nearly identical code

The only difference between the two nearly identical methods is DoA() calls MyA() while DoB() calls MyB(); and the parameters for DoA and DoB differ in both type and number.
    private class DoA(string x)
    {
       ... identical code ...
           string result = MyA();
       ... more identical code ...
    }

    private class DoB(string x, int y)
    {
       ... identical code ...
           string result = MyB();
       ... more identical code ...
    }

Open in new window

How can I factor out all that identical code? The calls to MyA() and MyB() are inside a loop.
deleydAsked:
Who is Participating?
 
Miguel OzSoftware EngineerCommented:
You should pass method as parameter (using delegates)

public delegate string MyDelegateMethod();
private class DoCommon(string x, int y, MyDelegateMethod myMethod)
{
       ... identical code ...
           string result = myMethod();
       ... more identical code ...
}

Open in new window


Note If you have modern version of C# you can use functions:
private class DoCommon(string x, int y, Func<string> myMethod)
{
       ... identical code ...
           string result = myMethod();
       ... more identical code ...
}[/code]

usage for B
DoCommon(x, y, MyB);

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.