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?
You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.
A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods.
delegate void MyDelegate( int x ); then it is not possible to perform such overloading.
This Func delegate takes two parameters and returns a single value. In the following example, we use a delegate with three input parameters.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With