0

Recently had a quiz in my C# class and got some things wrong. I think I have the answers but I want to make sure I am right.

First one:

Explain the result

int[] myArray = {5,10,15,20,25};
DoWork(myArray);

void DoWork(int[] theArray)
{
    for (int c = 0; c < theArray.Length; c++)
    {
        theArray[c] = 1;
    }
    theArray = null;
}

For this one, I only got half of it right. I said that the loop would set the value for each element in the array to 1. So my question is, what happens when you set the array to null?

Second one:

Explain the result

int[] myArray = {5,10,15,20,25};
DoWork(myArray[1]);

void DoWork(int theItem)
{
    theItem = -1;
}

This one I got completely wrong. The correction was that myArray[1] = 10 still. Is this because it is not being passed by reference? This just confused me a lot because I ran a little test program on the first one (without the null part) and all the values were set to 1 in the array but I was not passing by reference.

4
  • 2
    I'll take a crack at this... myArray is a REFERENCE to an object (an integer array object). Therefore, the first example simply sets the reference to NULL. In the second example, the second element is being passed to DoWork as a value. Therefore, changing the value of theItem has no bearing on the array itself. Commented Feb 24, 2016 at 18:34
  • 1
    @MatthewWatson No, that's not true at all. All parameters are passed by value unless they're explicitly marked as ref parameters, and then they're passed by reference. What the type of the parameter is is irrelivant. Commented Feb 24, 2016 at 18:49
  • 1
    @MatthewWatson - Arrays are not "always passed by reference". Here, a reference to the array is passed by value. Please delete your comment. Commented Feb 24, 2016 at 18:55
  • @paulsm4 How do you know that it is a reference to the array? Commented Feb 24, 2016 at 19:04

1 Answer 1

4

Q: what happens when you set the array to null?

A: "theArray" (inside the routine) is set to null. But "myArray" (outside of the routine) is UNCHANGED. The reason is that "myArray" is an object reference, which is passed by value into DoWork().

Q: Is this because it is not being passed by reference?

A: Yes, exactly. From the link above:

https://msdn.microsoft.com/en-us/library/9t0za5es.aspx

Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable.

These links explain further:

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

Comments

Your Answer

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.