By default all parameters in C# are passed by value. This is a very
subtle
concept in that the _variable_ to a reference type is passed by value,
not the
object. A copy of the variable goes on the stack. When the method
returns,
the variable is cleared off the stack. You can touch the actual object
from
within the method using the copy of the variable and IF the object is
mutable,
you can change the state of the object and this change will persist when
the
method returns. Unfortunately, in your example, you used an immutable
object. The local copy of the variable is assigned to a new immutable
string
and then the copy is cleaned off the stack. To prove the subtle
difference
between _effective_ pass by reference and true pass by reference, you
only
need to write a swap routine. The swap routine does not work as you
would
expect if C# supported true pass by refererence by default. To write a
swap
routine in C# you need to use the ref keyword.
This topic has been a source of great confusion to C++ coders, so I will
elaborate. If you want to write a swap routine then you need to add
another
degree of indirection to the method call. You can do this by use the
keyword
ref. Here is some sample code that demonstrates the concept. The swap
routine only works if you pass a reference to a concrete Drawable object
by
reference.
using System;
namespace TestSwap
{
abstract class Drawable
{
abstract public void DrawMe();
}
class Circle : Drawable
{
public override void DrawMe()
{
System.Console.WriteLine("Circle");
}
}
class Square : Drawable
{
public override void DrawMe()
{
System.Console.WriteLine("Square");
}
}
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static public void SwapByValue(Drawable d1, Drawable d2)
{
Drawable temp= d1;
d1 = d2;
d2= temp;
}
static public void SwapByRef(ref Drawable d1, ref
Drawable d2)
{
Drawable temp= d1;
d1 = d2;
d2= temp;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Drawable wasCircle= new Circle();
Drawable wasSquare= new Square();
wasCircle.DrawMe(); // outputs Circle
wasSquare.DrawMe(); // outputs Square
SwapByValue(wasCircle, wasSquare); // fails
wasCircle.DrawMe(); // outputs Circle
wasSquare.DrawMe(); // outputs Square
SwapByRef(ref wasCircle, ref wasSquare); //
succeeds
wasCircle.DrawMe(); // outputs Square
wasSquare.DrawMe(); // outputs Circle
System.Console.ReadLine();
}
}
}
Regards,
Jeff
*** Sent via Developersdex
http://www.developersdex.com ***