# How to avoid recursive and or infinity loop monogame return function

This piece of code is returning on a infinite base how to fix?

public GuiElement MoveElement(int x, int y)
{
GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
return MoveElement(x,y);
}


this is where i set the values i have in my Other class

        gm.Add(new GuiElement("BackGround"));



basicly i want a to be able to move some elements using that MoveElement

it creates a infinite loop

An unhandled exception of type 'System.StackOverflowException' occurred in giftman.exe

• What's the base case for your recursion? What's the code supposed to do? Please don't revert the edits again. Commented Feb 16, 2016 at 19:01
• its supposed to return some values i have set in another another class Commented Feb 16, 2016 at 19:02
• And the base case for the recursion? You can edit your question to include additional information. Commented Feb 16, 2016 at 19:02
• I don't understand the need for recursion in this case. For your statement to work, your method would have to return this; Commented Feb 16, 2016 at 19:08
• i might have missunderstood it however it creates a infinite loop which is what i am trying to get around Commented Feb 16, 2016 at 19:11

You don't need to use recursion for this (and without a base case, you'll get an infinite loop, like you are).

public GuiElement MoveElement(int x, int y)
{
GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
return this;
}


Or better yet, add a constructor to set the position of your GuiElement, so you can just call it like this:

gm.Add(new GuiElement("Play_Button", 150, 50));


Or you can just change your MoveElement method to not return anything at all:

public void MoveElement(int x, int y)
{
GUIRect = new Rectangle(GUIRect.X += x,GUIRect.Y += y,GUIRect.Width,GUIRect.Height);
}


Then when creating it you can do this:

GuiElement playButton = new GuiElement("Play_Button");
playButton.MoveElement(150, 50);

• Depending on how you have things set up, you'll likely have to reinitialize some aspects of the GuiElement, since all you're doing in MoveElement is creating a new rectangle. For example, the renderer might only look at the rectangle once at initialization, and not update itself if the rectangle is replaced. But that's something that'll be specific to your code. Commented Feb 16, 2016 at 19:42