I was wondering if any one could explain this code to me...
public void SomeMethod()
{
StringBuilder sb = new StringBuilder();
AppendFoo(sb);
String foo = sb.ToString(); // foo is "foo"
String s = String.Empty;
AppendBar(s);
String bar = s; // bar is empty
}
public void AppendFoo(StringBuilder x)
{
x.Append("Foo");
}
public void AppendBar(String x)
{
x = x + "Bar";
}
If both StringBuilder
and String
are reference types, why is the string object not altered when passing it through the AppendBar
method, whereas the StringBuilder object is altered when passing it into the AppendFoo
method, as the both parameters to the methods are taking reference types as parameters?