Example of practical of "ref" use

Loj picture Loj · Jan 10, 2011 · Viewed 8.6k times · Source

I am struggling how to use "ref" (to pass argument by reference) in real app. I would like to have simple and mainly meaningful example. Everything I found so far could be easily redone with adding return type to the method. Any idea someone? Thanks!

Answer

digEmAll picture digEmAll · Jan 10, 2011

The best example coming in my mind is a function to Swap two variables values:

static void Swap<T>(ref T el1, ref T el2)
{
    var mem = el1;
    el1 = el2;
    el2 = mem;
}

Usage:

static void Main(string[] args)
{
    string a = "Hello";
    string b = "Hi";

    Swap(ref a, ref b);
    // now a = "Hi" b = "Hello"

    // it works also with array values:
    int[] arr = new[] { 1, 2, 3 };
    Swap(ref arr[0], ref arr[2]);
    // now arr = {3,2,1}
}

A function like this one, cannot be done without the ref keyword.