C # pass objects by value?

For some reason (I'm new to C # and know java and C ++). C # saves copies of objects when I want to pass a value. I have an arraylist of class Vector2 , and whenever I want to increase the value, I have to do this:

 Vector2 d = (Vector2) myObjects[i]; d.Y++; myObjects [i] = d; 

I want to be able to do this:

 Vector2 d = (Vector2) myObjects[i]; d.Y++; 

and do it. I searched the Internet and, surprisingly, no answers. BTW vector is a structure.

+6
source share
2 answers

In C # instances of class es are passed as references, while struct instances are passed in by copy (by default).

The answer was exactly where it should have been: http://msdn.microsoft.com/en-us/library/vstudio/ms173109.aspx

The class is a reference type. When the class object is created, the variable to which the object is assigned contains only a reference to this memory. When an object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable, since both relate to the same data.

Structure is a type of value. When a structure is created, the variable to which the structure is assigned contains the actual structure data. When a struct is assigned to a new variable, it is copied. Therefore, the new variable and the original variable contain two separate copies of the same data. Changes made to one copy do not affect another copy.

+8
source

You experience one of the effects of value types. Because it copies itself by value, and not by reference when assigned to new variables, or passed as an argument.

You can pass a structural or other type of value using ref using the ref keyword in your method signature, unfortunately you cannot use it to process a variable in the same frame stack as the link (i.e. t just say ref int test = yourArray[0] , but you need to do something like:

 public void SomeMethod(ref Vector2 input) { // now you are modifying the original vector2 } public void YourOriginalMethod() { SomeMethod(yourArray[20]); } 

In response to the comment below, http://msdn.microsoft.com/en-us/library/14akc2c7.aspx :

Do not confuse the concept of transmission by reference with the concept of reference types. These two concepts do not match. The method parameter can be changed using ref regardless of whether it is a value type or a reference type. There is no value type box when it is passed by reference.

+3
source

Source: https://habr.com/ru/post/956298/


All Articles