I'm a Java programmer. I have little knowledge on C#. But from the blogs I have read, Java supports only pass-by-value-of-reference whereas in C# the default is pass-by-value-of-reference but the programmer can use pass by reference if needed.
I have penned down my understanding of how a swap function works. I guess it is crucial to get this concept clear as it is very fundamental to programming concepts.
In C#:
public static void Main()
{
String ONE = "one"; //1
ChangeString(ONE); //2
Console.WriteLine(ONE); //3
String ONE = "ONE"; //4
ChangeString(ref ONE); //5
Console.WriteLine(ONE); //6
}
private static void ChangeString(String word)
{
word = "TWO";
}
private static void SeedCounter(ref String word)
{
word = "TWO";
}
Step 1: A string object with value
one
is created on heap and the address of its location is returned stored in variableONE
. Runtime Environment allocates a chunk of memory on the heap and returns a pointer to the start of this memory block. This variableONE
is stored on the stack which is a reference pointer to the locate the actual object in memoryStep 2: Method
changeString
is called. A copy of the pointer (or the memory address location) is assigned to the variable word. This variable is local to the method which means when the method call ends, it is removed from stack frame and is out of scope to be garbage collected. Within the method call, the variable word is reassigned to point to a new location whereTWO
object sits in memory. method returnsStep 3: Printing on the console should print
ONE
, since what was changed in the previous step was only a local variableStep 4: Variable one is reassigned to point to the memory location where object
ONE
resides.Step 5: method
changeString
is called. This time reference to theONE
is passed. what this means is the local method variable word is an alias to the variable one in the main scope. So, no copy of reference is done. Hence it is equivalent in thinking that the same variable one is passed to the method call. The method reassigns the variable to point to a different memory location which happens to holdTWO
. The method returnsStep 6: Now the variable
one
on the outer scope i.e., in the main method is changed by method call and so it printsTWO
.
In Java
, step 5 is not possible. That is you cannot pass by reference
.
Please correct if the programming flow I described above is correct?