When is a C# value/object copied and when is its reference copied?

It’s hard to answer this sort of question precisely without spending an awful lot of time picking your words carefully.

I’ve done so in a couple of articles which you may find useful:

That’s not to say that the articles are perfect, of course – far from it – but I’ve tried to be as clear as I can.

I think one important thing is to separate the two concepts (parameter passing and reference vs value types) out in your head.

To look at your specific examples:

SomeForm myForm = new SomeForm();
SomeObject myObject = new SomeObject();
myForm.formObject = myObject;

This means that myForm.formObject and myObject refer to the same instance of SomeObject – like two people having separate pieces of paper, with each one having the same address written on them. If you go to the address on one piece of paper and paint the house red, then go to the address on the second piece of paper, you’ll see a red house.

It’s not clear what you mean by “and then modify the object in the form” because the type you have provided is immutable. There’s no way of modifying the object itself. You can change myForm.formObject to refer to a different instance of SomeObject, but that’s like scribbling out the address on one piece of paper and writing a different address on it instead. That won’t change what’s written on the other piece of paper.

If you could provide a short but complete program whose behaviour you don’t understand (ideally a console application, just to keep things shorter and simpler) it would be easier to talk about things in concrete terms.

Leave a Comment