Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to refactor this into a single method

Tags:

c#

I have a bunch of methods that look like these two:

   public void SourceInfo_Get()    
   {
        MethodInfo mi = pFBlock.SourceInfo.GetType().GetMethod("SendGet");
        if (mi != null)
        {
            ParameterInfo[] piArr = mi.GetParameters();
            if (piArr.Length == 0)
            {
                mi.Invoke(pFBlock.SourceInfo, new object[0]);
            }
        }
    }
    public void SourceAvailable_Get()
    {
        MethodInfo mi = pFBlock.SourceAvailable.GetType().GetMethod("SendGet");
        if (mi != null)
        {
            ParameterInfo[] piArr = mi.GetParameters();
            if (piArr.Length == 0)
            {
                mi.Invoke(pFBlock.SourceAvailable, new object[0]);
            }
        }
    }

I have one method for each property in my pFBlock object. with so little changing between methods I feel like there should be a better way to do this, but I can't think of any. I'm using VS 2005.

like image 476
scott Avatar asked Nov 22 '10 14:11

scott


1 Answers

How about 3 methods?

public void SourceInfo_Get()    
{
    SendGet(pFBlock.SourceInfo);
}

public void SourceAvailable_Get()
{
    SendGet(pFBlock.SourceAvailable);
}

private void SendGet(Object obj) {
    MethodInfo mi = obj.GetType().GetMethod("SendGet");
    if (mi != null)
    {
        ParameterInfo[] piArr = mi.GetParameters();
        if (piArr.Length == 0)
        {
            mi.Invoke(obj, new object[0]);
        }
    }
}

The idea here is to add a helper method that you can pass a parameter into. You can then use the helper method in your other methods to drastically shorten your code.

like image 167
jjnguy Avatar answered Oct 06 '22 17:10

jjnguy