How should I pass an array by value? Isn't Clone() discouraged?
I've been debugging a C# program of mine, and after several fruitless spans of time, discovered the error came from "accidentally" passing an array by reference instead of by value.
Here's some pseudocode:
//1st pass currentVertices = levels.vertices; currentVertices.Position.Z -= 10; //2nd pass currentVertices = levels.vertices; currentVertices.Position.Z -= 10; //3rd pass currentVertices = levels.vertices; currentVertices.Position.Z -= 10; //currentVertices.Position.Z is now 10 less than expected; //20 less than it started. Further loops will increase the difference in expected //value.
I was not expecting to have passed the Array by reference, but I accidentally did so anyway.
Is there a way to assign an array by value instead of by reference? I know that I could iterate through both arrays, assigning each term individually, but that seems unnecessarily complex. I'm reasonably sure that the Clone() function, well, clones, the values without the respective references, but is that the only way to assign by value? I.e. currentVertices = levels.vertices.Clone();
Isn't Clone() generally discouraged? What's the best practice for passing arrays by value?
In the short term, I've simply hardcoded what the values should be after being loaded.
"I see you solved pass-by-reference through by-pass-reference."
Well, in C# only value types are passed "by value". (This is an oversimplification, but that is a decent way to look at it.) Every thing else is actually a reference that is passed by value, which is similar to passing a pointer. (Note that this is different to passing "by ref", which would allow the update of a variable in a calling method.)
You have two options:
- refactor your code to avoid mutating the objects in the array
- deep-clone the array
Those are roughly in the order that I would recommend.