Sunday, May 27, 2007
Recently, I came across some C# code that was passing a reference type to a method using the 'ref' keyword. Since reference types are inherently passed by reference I was curious what effect the 'ref' keyword would have.

One of my colleagues speculated it would work like a double dereference in C++ and a little experimentation proved him correct.

The 'ref' keyword can be used to pass the reference of the reference to the object which allows the method to assign a different object to be returned via the parameter

[Test]
public void TestPassingClassBasedObjectsByRef( )
{
    string str1 = "initial value";


    PassStringInNormalWay( str1 );
    Assert.AreEqual("initial value", str1, "str1 object is not altered" );

    PassStringByReference( ref str1); 
    Assert.AreEqual("a", str1, "str1 is now a different object");
}

public void PassStringInNormalWay( string str )
{
    str = new string( 'new value', 1 );
}

public void PassStringByReference( ref string str)
{
    str = new string('new value', 1);
}

Sunday, May 27, 2007 10:42:24 PM (GMT Daylight Time, UTC+01:00)
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):