C# – Passing a delegate with two parameters as a parameter function

c++delegates

I have a sequence of functions that look very similar but for a single line, like the following two (but I have many more of them):

private static int HowManyHoursInTheFirstYear(IList<T> samples)
{
    DateTime firstDate = samples[0].Date;
    int count = 0;

    while (count < samples.Count && 
          samples[count].Date.Year == firstDate.Year)
    {
        count++;
    }

    return count;
}


private static int HowManyDaysInTheFirstMonth(IList<T> samples)
{
    DateTime firstDate = samples[0].Date;
    int count = 0;

    while (count < samples.Count && 
           samples[count].Date.Month == firstDate.Month) // <--- only change!
        count++;
    }

    return count;
}

I was thinking about using delegates to remove this repetition in code in some elegant way, that would have allowed me to invoke something like:

HowManyDaysInTheFirstPeriod(
    samples,
    delegate(DateTime d1, DateTime d2) { return d1.Month == d2.Month; });

thereby declaring a delegate like the following:

delegate bool DateComparer(DateTime first, DateTime second);

and where HowManyDaysInTheFirstPeriod whould be something like the following:

private static int HowManySamplesInFirstPeriod
    IList<T> samples,
    DateComparer comparer)
{
    DateTime firstDate = samples[0].Date;
    int count = 0;

    while (count < samples.Count && comparer())
    {
        count++;
    }
}

Unfortunately, the compiler complains that comparer needs two parameters.

I am relatively new to C# and hit a road-block here.
How would you solve this?

Best Solution

You're almost there! The comparer delegate parameter is just like any other function: You still need to pass the appropriate arguments to invoke it. In your case, that's going to mean this change:

while (count < samples.Count && comparer(samples[count].Date, firstDate))
{
    count++;
}

(Also, note that samples should probably be samples.Count, as I have written above.)