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 - oneis created on heap and the address of its location is returned stored in variable- ONE. Runtime Environment allocates a chunk of memory on the heap and returns a pointer to the start of this memory block. This variable- ONEis stored on the stack which is a reference pointer to the locate the actual object in memory
- Step 2: Method - changeStringis 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 where- TWOobject sits in memory. method returns
- Step 3: Printing on the console should print - ONE, since what was changed in the previous step was only a local variable
- Step 4: Variable one is reassigned to point to the memory location where object - ONEresides.
- Step 5: method - changeStringis called. This time reference to the- ONEis 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 hold- TWO. The method returns
- Step 6: Now the variable - oneon the outer scope i.e., in the main method is changed by method call and so it prints- TWO.
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?
 
     
     
    