richard
richard

Reputation: 12554

What's really on the Form?

If I have this code:

Label label1 = new Label();  
Form1.Controls.Add(label1);  
Label label2 = label1;

What's really on From1? Is it label1? Or is it the object label1 points to?

In other words if I then have this:

Form1.Controls.Remove(label1);

have I effectively removed the label? Or is label2 keeping it on the form?

I guess I'm wondering, is it the pointer that's on the Form, or is it the object the pointer points to?

Upvotes: 3

Views: 102

Answers (4)

Jeb
Jeb

Reputation: 3799

You've added the label object label1 references to the form, and just assigned another reference to it using label2. If you remove label1 from the form's control list, you've removed the form's reference to the label object, but label1 and label2 still point to the object hence the label object won't be garbage collected until they fall out of scope.

Upvotes: 1

itsme86
itsme86

Reputation: 19526

Controls.Add() adds a reference to whatever Control you pass to it. label2 = label1 just creates another reference to label1. Controls.Remove() doesn't delete the object, it just removes it from its list of controls.

So, in your example, after you call Controls.Remove():

  • label1 would still "exist" (i.e. it will not be garbage collected).
  • label2 would reference label1.
  • The label would not still be part of the form because the form's list of controls no longer contains a reference to the label.

Upvotes: 3

Tigran
Tigran

Reputation: 62265

Yes, it will remove the label1 from the Form. I would say that even the code like this

Form1.Controls.Remove(label2) will remove the label control from the Form as their both point on the exactly same UI object.

Upvotes: 3

Fredrik Mörk
Fredrik Mörk

Reputation: 158399

label1 and label2 are merely variables containing a reference to the object. Both of them are referencing the same Label instance. When calling Controls.Add, the Controls collection also get a reference to the Label instance, and it may be rendered within the bounds of the Form (if it's visible and has coordinates that are withing the visible portion of the form, that is).

Upvotes: 1

Related Questions