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

后端 未结 3 1249
借酒劲吻你
借酒劲吻你 2020-11-27 15:12

I keep getting the same issue over and over again where an object I want to reference is copied or where an object I want to copy is referenced. This happens when I use the

3条回答
  •  不知归路
    2020-11-27 15:27

    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 :)

提交回复
热议问题