Chris S. wrote:
In reference to the above about strings, they behave like value types.
Well, I think it's more accurate to say that they behave like immutable
reference types. When you pass them around, a reference is passed, not
the actual text data.
If you treat it like a value type, you *might* be tempted to pass it by
reference for efficiency reasons if you've got a large string - when in
fact it would have no performance benefit (and may even harm
performance slightly).
I don't know the internal workings well enough to say whether a
reference is passed or not, however use them like value types is the
easiest solution. e.g.:
private void button1_Click(object sender, System.EventArgs e)
{
string s = "moo";
this.foo(s);
MessageBox.Show(s);
}
private void foo(string s)
{
s = "hello";
}
Displays a message box with "Moo", not "hello".
Indeed, and if you use any other type it would do the same thing there,
because s is not passed *by* reference. Changing the value of a
parameter doesn't change the value used for the argument unless it's an
argument which is passed by reference.
Now, not that changing the contents of an object that a parameter
refers to is not the same thing.
To make this concrete, I think we can all agree that StringBuilder is a
reference type. If you changed your foo method to:
private void foo (StringBuilder sb)
{
sb = new StringBuilder ("hello");
}
you'd still see the same behaviour - the caller wouldn't notice
anything.
If you changed the method to:
private void foo (StringBuilder sb)
{
sb.Append ("hello");
}
*then* they'd notice a difference.
And that highlights the difference between String and StringBuilder -
String doesn't have any methods which change the data stored in the
String; it's immutable.
Knowing this difference is important because it suggests that often
when you want what are often called "value type semantics" you can
achieve them with something which is still very definitely a reference
type, by making it immutable (at least to the outside world) in the
same way that String is immutable.
Jon