How can I avoid redundant comparisons when checking rectangle overlaps in C#?

1 day ago 3
ARTICLE AD BOX

I have a C# console application that reads button data from a CSV file and stores the buttons in a List<MyButton>. One part of the task is checking whether any buttons overlap on a 2D plane.

This is my current implementation:

bool hasOverlap = false; for (int i = 0; i < buttons.Count; i++) { for (int j = 0; j < buttons.Count; j++) { if (i != j) { MyButton firstButton = buttons[i]; MyButton secondButton = buttons[j]; bool isOverlapping = firstButton.Left < secondButton.Left + secondButton.Width && firstButton.Left + firstButton.Width > secondButton.Left && firstButton.Top < secondButton.Top + secondButton.Height && firstButton.Top + firstButton.Height > secondButton.Top; if (isOverlapping) { hasOverlap = true; } } } }

The code works, but I suspect it checks the same pairs multiple times in different order (A vs B and B vs A).


Additional context

The buttons are loaded from a CSV file and stored like this:

internal class MyButton { public string MyEvent { get; set; } public int Left { get; set; } public int Top { get; set; } public int Width { get; set; } public int Height { get; set; } public string Text { get; set; } }

Question

What is the most readable way to avoid redundant comparisons in this kind of overlap detection logic, while keeping the solution simple and idiomatic in C#?

Read Entire Article