c# - Creating an object of Form1 causes a stack overflow -



c# - Creating an object of Form1 causes a stack overflow -

i have label in form1 i'm trying modify. here's code:

namespace asst5 { public partial class form1 : form { robot robot1 = new robot(); public form1() { initializecomponent(); label2.location = new point(100,100); label1.text = label2.location.tostring(); } private void button7_click(object sender, eventargs e) { application.exit(); } private void button1_click(object sender, eventargs e) { label2.text = "↑"; robot1.direction = 1; } private void button2_click(object sender, eventargs e) { label2.text = "↓"; robot1.direction = 2; } private void east_click(object sender, eventargs e) { label2.text = "→"; robot1.direction = 4; } private void west_click(object sender, eventargs e) { label2.text = "←"; robot1.direction = 3; } private void button6_click(object sender, eventargs e) { robot1.speed = 1; robot1.move(); } private void button5_click(object sender, eventargs e) { robot1.speed = 10; robot1.move(); } } public class robot { form1 frm1 = new form1(); public int direction = 1; //1 = north, 2 = south, 3 = west, 4 = east public int speed = 1; public void move() { if (direction == 1) { frm1.label2.location = new point(frm1.label2.location.y - speed); } if (direction == 2) { frm1.label2.location = new point(frm1.label2.location.y + speed); } if (direction == 3) { frm1.label2.location = new point(frm1.label2.location.x - speed); } if (direction == 4) { frm1.label2.location = new point(frm1.label2.location.x + speed); } } } }

form1 frm1 = new form1(); stack overflow occurs. i'm sure isn't proper way of doing when seek otherwise tells me 'an object reference required non-static field.'

you have recursive declaration.

form1 instantiates robot ... instantiates form1 ... goes around in circles until blow stack.

what want do, pass instance of form1 robot. firstly, remove form1 frm1 = new form1(); line. then, introduce field:

form1 frm1;

then, create constructor in robot:

public robot(form1 frm) { frm1 = frm; // pass form in }

then, in form1 class, instantiate robot in constructor passing in instance of form:

robot robot1; public form1() { initializecomponent(); label2.location = new point(100,100); label1.text = label2.location.tostring(); robot1 = new robot(this); // "this" form1 instance }

c# class object instance stack-overflow

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -