Search code examples
c#methodsoverlap

How to Determine if Two Shifts Overlap in C#?


I'm currently working on a project where I need to determine whether two shifts overlap in C#. Each shift is represented by a ShiftType class, containing start and end hours.

Here's an example of the ShiftType class:

public class ShiftType
{
    public string Id { get; set; }
    public int StartHour { get; set; }
    public int EndHour { get; set; }
}

I need to write a method that checks if two shifts overlap. For instance, if shift A starts at 6 and ends at 14, and shift B starts at 14 and ends at 22, they don't overlap. However, if shift C starts at 22 and ends at 7 (crosses midnight), it overlaps with shift A because it extends into the next day.

I've attempted to implement a method using comparisons of start and end hours, but I'm struggling to handle cases where one shift extends into the next day. How can I properly implement this functionality to accurately determine if two shifts overlap?

Any guidance or code examples would be greatly appreciated. Thank you!


Solution

  • You could add this method to your class:

    public bool OverlapsWith(ShiftType other)
    {
        bool thisIsNightShift = StartHour > EndHour;
        bool otherIsNightShift = other.StartHour > other.EndHour;
        if (thisIsNightShift == otherIsNightShift) // either both true or false
        {
            return StartHour < other.EndHour && EndHour > other.StartHour;
        }
        else
        {
            return StartHour < other.EndHour || EndHour > other.StartHour;
        }
    }
    

    Tested with your samples and worked as desired:

    ShiftType a = new ShiftType() { Id = "1", StartHour = 6, EndHour = 14 };
    ShiftType b = new ShiftType() { Id = "2", StartHour = 14, EndHour = 22 };
    ShiftType c = new ShiftType() { Id = "3", StartHour = 22, EndHour = 7 };
    bool aOverlapsWithB = a.OverlapsWith(b); // false
    bool aOverlapsWithC = a.OverlapsWith(c); // true
    bool cOverlapsWithA = c.OverlapsWith(a); // true
    bool cOverlapsWithB = c.OverlapsWith(b); // false