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

徘徊边缘 提交于 2019-11-26 20:13:04

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.

Hi Mike All objects, which derives from ValueType, such as struct or other primitive types are value types. That means that they are copied whenever you assign them to a variable or pass them as a method parameter. Other types are reference types, that means that, when you assign a reference type to a variable, not it's value, but it's address in memory space is assigned to the variable. Also you should note that you can pass a value type as a reference using ref keyword. Here's the syntax

public void MyMethod(ref int a) { a = 25 }
int i = 20;
MyMethod(ref i); //Now i get's updated to 25.

Hope it helps :)

With regards to cloning your objects if the values you are copying from one object to another are reference types then any modification to those values in the original object will affect the values in the copied object (since they are just references to the same object)

If you need to clone an object which has properties which are reference types you need to either make those types clonable or do a manual copy of them by instantiating new instances as required.

Conside using the IClonable interface though it isn't the best of solutions imho.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!