I guess it's rather stupid question. I开发者_运维技巧 want to pass an array argument to method by value, not by link, i.e. I want to make a copy of object to prevent changing of argument inside the method. Thanks in advance.
If your method acts destructively on its parameter's contents, simply make a copy of the array inside the method.
This is as simple as
var copy = parameter.ToArray();
if you are using LINQ, otherwise it can also be done easily with Array.Copy
.
This is much better than copying before calling the method (as you mention in the question), because you can always forget to do that. Copying inside the method leaves no possibility of error.
Arrays are reference types. You can't have them automatically be cloned when passed to a method.
You have to make a clone manually and pass the resulting array to the method:
int[] array = ...
MyMethod((int[])array.Clone());
Note that this is an O(n) operation can can be quite slow for large arrays or many repeated calls.
There is no way to do this in C#. You will need to copy the array yourself, either inside the method, or on the calling side:
int[] array = GetIntArray();
CallSomeMethod(array.ToArray()); // ToArray() makes a copy of the input...
My understanding of the question in the OP is the poster is looking for a way to pass a reference type by value. I found this example:
class PassingRefByVal
{
static void Change(int[] arr)
{
//arr[0]=888; // This change affects the original element.
arr = new int[5] {-3, -1, -2, -3, -4}; // This change is local.
Console.WriteLine("Inside the method, the first element is: {0}", arr[0]);
}
public static void Main()
{
int[] myArray = {1,4,5};
Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", myArray [0]);
Change(myArray);
Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", myArray [0]);
Console.ReadLine();
}
}
here: http://msdn.microsoft.com/en-us/library/0f66670z(v=vs.71).aspx
Hope this is what you're looking for.
精彩评论