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[0].vertices;   
currentVertices[0].Position.Z -= 10;

//2nd pass
currentVertices = levels[1].vertices;
currentVertices[0].Position.Z -= 10;

//3rd pass
currentVertices = levels[0].vertices;
currentVertices[0].Position.Z -= 10;  

//currentVertices[0].Position.Z is now 10 less than expected;
//20 less than it started. Further loops will increase the difference in expected

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[1].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.

As one of my moderator friends remarked,

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

  1. refactor your code to avoid mutating the objects in the array
  2. deep-clone the array

Those are roughly in the order that I would recommend.

Need Your Help

Adding a parameter to a public template

c++ api templates design

I have a templated API function that looks like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.