2

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.

asked Jan 10, 2011 at 20:42
1
  • 1
    Changing the argument is never a problem, that doesn't propagate back. Only changing the array content. Commented Jan 10, 2011 at 20:59

4 Answers 4

8

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.

answered Jan 10, 2011 at 20:44

Comments

4

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.

answered Jan 10, 2011 at 20:45

Comments

1

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...
answered Jan 10, 2011 at 20:45

Comments

1

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.

answered Jan 10, 2011 at 21:00

1 Comment

Isn't that just the standard way of passing an array argument?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.