Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# is passing objects by value?

Tags:

c#

For some reason, (I am new to C# and know java and c++) C# keeps copying objects when I want to pass by value. I have an arraylist of a Vector2 class, and whenever I want to increment a 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 be done. I searched the web and surprisingly no answers. BTW the vector is a struct.

like image 702
Susan Yanders Avatar asked Oct 19 '13 01:10

Susan Yanders


2 Answers

You are experiencing one of the effects of value-types. Because it copies itself by value, rather than by reference when assigned to new variables or passed as an argument.

You can pass a struct or other value type by ref, using the ref keyword in your method signature, unfortunately you can't use it for treating a variable in the same stack frame as a reference (i.e. you can't just say ref int test = yourArray[0], but must make 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, from http://msdn.microsoft.com/en-us/library/14akc2c7.aspx:

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.

like image 55
Rob G Avatar answered Oct 23 '22 07:10

Rob G


In C#, instances of classes are passed as references, whereas instances of structs are passed by copy (by default).

The answer was just where it was supposed to be: http://msdn.microsoft.com/en-us/library/vstudio/ms173109.aspx

A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the 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 because they both refer to the same data.

A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.

like image 22
Giulio Franco Avatar answered Oct 23 '22 08:10

Giulio Franco