-3

To keep an integer within certain bounds, currently I'm doing:

frame.X = frame.X <= 0 ? 0 : frame.X;
frame.X = frame.X + frame.Width > Image.Width ? Image.Width - frame.Width : frame.X;

frame.Y = frame.Y <= 0 ? 0 : frame.Y;
frame.Y = frame.Y + frame.Height > Image.Height ? Image.Height - frame.Height : frame.Y;

Is there a cleaner way for bound checking?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

2 Answers2

2

For compactness (although not performance) you could consider something like this:

frame.X = Math.Min(Image.Width - frame.Width, Math.Max(0, frame.X));
frame.Y = Math.Min(Image.Height - frame.Height, Math.Max(0, frame.Y));
AlexD
  • 32,156
  • 3
  • 71
  • 65
1

If you aim at a structural approach, you can use the extension methods

public static class IComparableExtensions
{

    public static T Min<T>(this T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) < 0 ? a : b;
    }

    public static T Max<T>(this T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) > 0 ? a : b;
    }

    public static T Clip<T>(this T a, T Min, T Max) where T : IComparable<T>
    {
        return a.Max(Min).Min(Max);
    }
}

to factor out the catual checking.

Codor
  • 17,447
  • 9
  • 29
  • 56