Originally Posted by
quzah
So you are saying that 'ref' basically makes a pointer to a pointer? That doesn't seem right, and while I'd have to look, I'm pretty sure I have used new in a method to fill something passed as an argument and had it work.
If the object is a value type, the 'ref' keyword passes it as a reference to a value.
If the object is a reference type, the 'ref' keyword passes it as a reference to a reference - behind the scenes it's basically implemented as a pointer to a pointer.
Try this:
Code:
using System;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i;
RefType j = new RefType();
i = 23;
j.Value = 42;
Console.WriteLine("Start: i = {0}, j = {1}", i, j.Value);
IntByVal(i);
Console.WriteLine("IntByVal: i = {0}, j = {1}", i, j.Value);
IntByRef(ref i);
Console.WriteLine("IntByRef: i = {0}, j = {1}", i, j.Value);
ObjByVal(j);
Console.WriteLine("ObjByVal: i = {0}, j = {1}", i, j.Value);
ObjByRef(ref j);
Console.WriteLine("ObjByRef: i = {0}, j = {1}", i, j.Value);
Console.WriteLine("Press Enter to continue");
Console.Read();
}
static void IntByVal(int i)
{
i = 30;
}
static void IntByRef(ref int i)
{
i = 97;
}
static void ObjByVal(RefType j)
{
j.Value = 36;
j = new RefType();
j.Value = 128;
}
static void ObjByRef(ref RefType j)
{
j.Value = 768;
j = new RefType();
j.Value = 90210;
}
}
class RefType
{
public int Value { get; set; }
}
}
IntByVal of course passes an integer by value, so it doesn't change the value of i or j in the main tag; only the local copy changes.
IntByRef changes the value of i in the main method because it has a reference.
ObjByVal sets j to have a value of 36. Changing its local j to refer to a new object does not change the caller.
ObjByRef sets j to have a value of 90210; changing the local j to refer to a new object does change the caller's variable also named j, because the reference itself was passed by reference.