Subject: Passing Reference Types by Value
Posted By: semiloof Post Date: 12/20/2003 2:46:23 PM
Is it possible to pass an array (a reference type) as a parameter to a function by value?  I simply want to pass a copy of an array through a function argument list - at present the function is destroying the array.

I could, of course, create a copy of the array and pass that through the argument list, but I feel that there must be a better solution.

Semiloof

Reply By: planoie Reply Date: 12/21/2003 11:16:40 PM
Found this MSDN article concerning array types in .net.  Here's an excerpt that addresses this topic:

Passing and Returning Arrays
    Arrays are always passed by reference to a method. Since the CLR doesn't support the notion of constant parameters, this means that the method is able to change the elements in the array. If you don't want to allow the method to modify the elements, then you must make a copy of the array and pass the copy into the method. Note that the Array.Copy method does a shallow copy, and therefore if the array's elements are reference types, the new array refers to the already existing objects.
    To obtain a deep copy, you may want to clone the individual elements, but this requires that each object's type implements the ICloneable interface. Alternatively, you could serialize each object to a System.IO.MemoryStream and then immediately deserialize the memory stream to construct a new object. Depending on the object's types, the performance of these operations can be prohibitive and not all types are serializable either.

Go to topic 7861

Return to index page 982
Return to index page 981
Return to index page 980
Return to index page 979
Return to index page 978
Return to index page 977
Return to index page 976
Return to index page 975
Return to index page 974
Return to index page 973