NCrontab
NCrontab copied to clipboard
Implement equality for 'ContrabSchedule'
There is currently no way to check a ContrabSchedule
object for equality against another schedule. It's also not possible to properly implement a custom EqualityComparer
from the outside since the fields that store the data inside the schedule are all private.
This could be fixed by implementing IEquatable<ContrabSchedule>
on the model.
I'll think about this but meanwhile…
There is currently no way to check a
ContrabSchedule
object for equality against another schedule.
The ToString()
implementation of ContrabSchedule
returns an expanded/lowered version of the one originally parsed expression:
https://github.com/atifaziz/NCrontab/blob/b6659e45d60de554c5619d7f35f39ad1114b6542/NCrontab/CrontabSchedule.cs#L376-L397
It can be used today as a good basis for equality comparison via an IEqualityComparer<CrontabSchedule>
implementation like so:
sealed class EqualityComparer<CrontabSchedule> : IEqualityComparer<CrontabSchedule>
{
public bool Equals(CrontabSchedule x, CrontabSchedule y) =>
x?.ToString() == y?.ToString();
public int GetHashCode(CrontabSchedule obj) =>
obj.ToString().GetHashCode();
}
Usage would then be:
var comparer = new EqualityComparer<CrontabSchedule>();
var schedule1 = CrontabSchedule.Parse("0-59 * * * Mon-Fri/2");
var schedule2 = CrontabSchedule.Parse("* * * * Fri,Mon,Wed");
var schedule3 = CrontabSchedule.Parse("* * * * *");
Console.WriteLine(comparer.Equals(schedule1, schedule2)); // True
Console.WriteLine(comparer.Equals(schedule1, schedule3)); // False
Console.WriteLine(comparer.Equals(schedule2, schedule3)); // False
Note how 0-59 * * * Mon-Fri/2
(schedule1
) and * * * * Fri,Mon,Wed
(schedule2
) compare equal even though they are expressed differently.