Home > Enterprise >  How to implement one method with different parameters. C#
How to implement one method with different parameters. C#

Time:09-27

guys, please tell me how this logic can be pulled into a separate method, since there is a duplication of code, but slightly different by the comparison operator. C#.

public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2)
        {
            if (r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom)
                return 0;
            if (r1.Left <= r2.Left && r1.Right >= r2.Right && r1.Top <= r2.Top && r1.Bottom >= r2.Bottom)
                return 1;
            return -1;
        }

CodePudding user response:

You could extract a somewhat simpler method

public static bool IsLeftRectangleCompletelyWithinRightRectangle(Rectangle r1, Rectangle r2)
{
    return (r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom)
}

and then use it like

public static int IndexOfInnerRectangle(Rectangle r1, Rectangle r2)
{
    if (IsLeftRectangleCompletelyWithinRightRectangle(r1, r2))
        return 0;
    if (IsLeftRectangleCompletelyWithinRightRectangle(r2, r1))
        return 1;
    return -1;
}

CodePudding user response:

I suppose you could have

    public static bool IsR1InsideR2(Rectangle r1, Rectangle r2)
    {
        return r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom);
    }

And then call it twice, swapping the rects over for the second call:

var a = ...
var b = ...

if(IsR1InsindeR2(a,b))
  return 0; //or whatever you did with the 0
if(IsR1InsindeR2(b,a))
  return 1; //or whatever
return -1; //or whatever

Making it an extension or instance method might improve readability:

    public static bool Inside(this Rectangle r1, Rectangle r2)
    {
        return r1.Left >= r2.Left && r1.Right <= r2.Right && r1.Top >= r2.Top && r1.Bottom <= r2.Bottom);
    }

    //usage
    a.Inside(b);

Also if these are System.Drawing.Rectangles check out their Contains method..

  •  Tags:  
  • c#
  • Related