-1

In C# and many other languages, if you pass an array to a function it passes the pointer/reference which means you can change the value of an array from inside a function.

From Microsoft:

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

I have a special case where I need to access and change an array's contents from a function but I do not want to change the original array. I thought this would be quite simple. I could set a new array equal to the old array and change the new array. This acts the same, however, because the new array is just a pointer to the old one.

static void AddToArray(string[] array) {
    var newArray = array;
    newArray[2] = "y";
}

static void Main(string[] args) {
    string[] array = new string[5];
    array[0] = "h";
    array[1] = "e";

    AddToArray(array);

}

If you print the contents of array at each step:

"he"
"hey" (inside function)
"hey" (after function call)

I've done a lot of research online but somehow haven't found many other people who needed help with this. Advice is greatly appreciated!

0

1 Answer 1

1

You are not creating your array using "new" Keyword inside function. Change below line -

var newArray = array;

To

var newArray = new string[args.Length];

and after creating this as a new array, you can copy the values from args (passed) array

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.