The two replies you already received are correct. Here is another way
of phrasing it.
You are, in a way, comparing apples and oranges. The case of ArrayList
and String are identical. You have the same capabilities and the same
thing is happening, but you're failing to see a distinction.
The distinction is this: when you pass an ArrayList, you can _change
the ArrayList_, but you _can't_ change _which ArrayList_ "ar" points
to. "ar" still points to the _same ArrayList as before_. It's just that
you've change _what_ that particular ArrayList _contains_.
If you try to write the code so that you try to change _which
ArrayList_ ar points to, you'll find that you can't:
public class arraylistchange
{
ArrayList ar ;
//This is passed in as a reference even if i dont specify ref.
// (So is a string, by the way.)
public arraylistchange(ArrayList arIn)
{
//This seems to be copied as a reference. So my member
//variable ar is a reference type even if i dont specify it to be?
// (The string variable was a reference type, too.)
ar = arIn ;
}
public void Change()
{
// Here we create a whole new ArrayList and change what
// this.ar points to.
ArrayList newOne = new ArrayList();
newOne.Add("123");
newOne.Add("456");
this.ar = newOne;
}
};
ArrayList ar = new ArrayList(10) ;
ar.Add("123") ;
arraylistchange archange = new arraylistchange(ar) ;
archange.Change() ;
int n = ar.Count ;//is *1*, because it still points to the original
ArrayList, not the new one
See? You can change the ArrayList itself, but if you change _which
ArrayList_ the field this.ar points to, the variable ar on the outside
doesn't change. It can't, because C# doesn't allow references to
references.
This is what is happening with strings. As C# Learner pointed out,
strings are immutable. In your string Change() method, you didn't say:
this.k.SetNewStringValue("Hello");
or something like that. You didn't _change the value of the string_.
You instead _changed which string_ this.k pointed to, because C# won't
let you change the values of strings, only create new ones and point
variables to the new string.
So, what you were doing in the two methods was different.
That's why I said that Strings, because of the way they're implemented
in C#, sort of act like value types. You can't point x to a string and
y to a string then "change the string" so that it changes in x and y,
because in C# you can't change strings. You can only change x to point
to a different string, which of course doesn't affect y at all.
ArrayLists and other reference types are different. You can change an
ArrayList: add items, remove items, etc. If x and y point to the same
ArrayList, and you change that ArrayList, both x and y will now point
to the changed ArrayList. However, as for strings, if you point x and y
to the same ArrayList and then create a new ArrayList and point x to
that, y remains unaffected.
Does that help?