Your analysis seems correct at the start, but your conclusions are not.
You have a reference type (an array) and you pass it to a method by value (which is the default). This means that the reference to that array, which sits on the heap, is copied.
Because both the variable in SpecialMethod
and Main
have the same reference, changing the value that they reference will be "seen" by both variables.
That only applies if you mutate the array. That's what you do with readToEnd
, which is why the sections of code dealing with it work as you intended.
With data
on the other hand you don't mutate the array, you just assign a new array to the variable. That's changing the reference, not the object that it references, and that's why you're having problems.
As for solutions, there are several. First, you could change the code to mutate the array rather than assigning a new one; just change the exising values. If you need to change the number of elements consider using a List
rather than an array.
Another option is, rather than passing an array, is to add another layer of indirection. You could make a new class that has a property which is an array, pass an object of that type to SpecialMethod
, and then you can change that object's property and see it reflected in both locations. You could use something like this to cover the general case:
public class Wrapper<T>
{
public T Value { get; set; }
}