1

If I were to do the following, do you consider that to be copying an object from one variable to another or referencing where the pointer to an object is copied.

myPanel:Panel;
myControl:Control;

myPanel := new Panel;

myControl := myPanel;

if this is not referencing, then changing any setting with myControl will not change myPanel setting. Am I correct in saying that?

marc hoffman
  • 586
  • 1
  • 5
  • 14
ThN
  • 3,235
  • 3
  • 57
  • 115
  • Does this code even compile? I will assume it does. All you are doing is setting the same reference to two different variables. They both reference the same object. – Security Hound Mar 05 '13 at 15:04
  • @Ramhound yes it does compile. So, the changes I apply with myControl variable should also be reflected on myPanel variable at the sametime pretty much. – ThN Mar 05 '13 at 15:07
  • Both variables point to the same object. As long as they are in the same block of code, using either one, would change the single object. Why are you doing this exactly? – Security Hound Mar 05 '13 at 15:13
  • @Ramhound, I am actually having problem with my program I am working on. I have a list of objects defined by a class. one of the object is a digital meter, which is based on a panel. I have to do a similar setup as above. My problem is that everytime I place this panel meter on the winform and drag its active bound moves as well micking my every mouse move. As a result, you eventually loose control of it. I have asked a question related to this problem on Stackoverflow. Take a look at it - http://stackoverflow.com/questions/15210229/why-is-panel-bound-moving-as-i-move-the-panel-itself – ThN Mar 05 '13 at 15:21

2 Answers2

1

Both myPanel and myControl are references. When you make the assignment you're copying a reference, not making a reference-to-a-reference. (Think about it as copying an address in memory if you like.)

However, when you call methods or set fields on myPanel or myControl, you're de-referencing, i.e. acting on the referenced object. This "changing settings" with myControl (I assume you mean setting fields) changes them in the same object referenced by myPanel.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
1

In .net, most types -- particularly stuff as complex as Windows controls -- are reference types. This means the variable's value is just a reference to an object, and you're just copying references -- not whole objects -- when you assign variables of those types. The big result being that in your example, changing myControl would change myPanel (and vice versa), because the two refer to the same object.

To be sure, check the documentation. If the object's type inherits from System.ValueType (or System.Enum, which extends ValueType as well), then it's a value type, and the whole thing will get copied when you assign. Otherwise it's a reference type, and you're just copying references.

cHao
  • 84,970
  • 20
  • 145
  • 172