Reference types are passed by value-by-value reference in .NET. This means that assigning a different value to the actual parameter does not actually change the original value (unless you use ByRef / ref). However, everything you do to change the actual object to be transferred will change the object referenced by the invocation method. For example, consider the following program:
void Main() { var a = new A{I=1}; Console.WriteLine(aI); DoSomething(a); Console.WriteLine(aI); DoSomethingElse(a); Console.WriteLine(aI); } public void DoSomething(A a) { a = new A{I=2}; } public void DoSomethingElse(A a) { aI = 2; } public class A { public int I; }
Output:
1 1 2
The DoSomething method assigned its parameter a to a different value, but this parameter is only a local pointer to the location of the original a from the calling method. Changing the value of a pointer did not change the value of the calling method a . However, DoSomethingElse did make a change to one of the values โโof the link object.
No matter what the other responders say, string not so exceptional. All objects behave in this way.
Where string differs from many objects in that it is immutable: there are no methods or properties or fields in the string that you can call to actually modify the string. Once a string is created in .NET, it is read-only.
When you do something like this:
var s = "hello"; s += " world";
... the compiler turns this into something like this:
// this is compiled into the assembly, and doesn't need to be set at runtime. const string S1 = "hello"; const string S2 = " world"; // likewise string s = S1; s = new StringBuilder().Append(s).Append(S2).ToString();
This last line generates a new line, but S1 and S2 are still hanging around. If they are constant lines embedded in the assembly, they will remain there. If they were created dynamically and no longer have references to them, the garbage collector can delete links to free memory. But the key is to understand that S1 has never changed. The variable pointing to it just changed to point to another line.
Stripling warrior
source share