1

I often have some piece of code that repeats.

Usually, I put them in a function, but sometimes I hate to do this because :

  • it requires too many parameters
  • the code is usually very specific to a little part of the whole. So I finally have two or three function that are only used in one place.

So, to simulate Inline code which is missing from C#, I use Action delegates :

public void Display(DateTime from, DateTime to)
{
    var start = from.ToOADate();
    var end = to.ToOADate();

    [...]

    // This Action delegate helps me not to repeat the code.
    var removePoints = new Action<Series>(serie =>
    {
        var pointsToRemove = serie.Points.Where(pt => pt.XValue < start || pt.XValue > end).ToArray();

        foreach (var pt in pointsToRemove)
            serie.Points.Remove(pt);
    });

    removePoints(FlameTemperatureSerie);
    removePoints(BoshGasFlowRateSerie);
    removePoints(PercCOSerie);
    removePoints(PercH2Serie);

    [...]
}

This is quite helpful, especially because the Action delegate execution context can use the local variables.

I seems good to me, but I never saw nowhere Action delegates used this way. That's why I would like to know if this practice could be recommended, or if might causes issues I dont know.

Larry
  • 17,605
  • 9
  • 77
  • 106
  • 1
    I missed this question where an answer can be found about this use case, plus a lot of Action delegate uses : http://stackoverflow.com/questions/371054/uses-of-action-delegate-in-c-sharp?rq=1 – Larry Feb 01 '13 at 13:53

2 Answers2

2

As long as it doesn't get too confusing, there is nothing wrong with that.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

It is perfectly valid to have a function that is only called once if it makes the code easier to read and maintain.

Mike B
  • 2,592
  • 3
  • 33
  • 46