11

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!

Loj
  • 1,159
  • 3
  • 14
  • 23

6 Answers6

22

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.

digEmAll
  • 56,430
  • 9
  • 115
  • 140
  • Excellent! Now I doubt I will be ever good programmer, this would never come to my mind. – Loj Jan 10 '11 at 11:36
  • 1
    @Loj: More than anything, I think what you should have learned from the answers to this question is that it's quite rare you'll have a use for the `ref` keyword. The fact that you couldn't think of it is no indication you're a bad programmer. – Cody Gray - on strike Jan 10 '11 at 11:41
  • @Loj: yes, Cody is right. I've used ref keyword more than rarely. I thought to the Swap function because is just the ref example I always remember (don't know why) – digEmAll Jan 10 '11 at 11:53
  • I think its really nice example as even for non generic types it makes the swapping elegant and easy. – Loj Jan 10 '11 at 11:55
  • I would be careful about this Swap as swapping a custom class that contains a string which the string will be swapped you don't need the REF because it's already a reference and only the data of the reference will be changed. When you pass the string you are trying to swap the reference itself. A good reference for that is here : http://stackoverflow.com/questions/1096449/c-sharp-string-reference-type So in a sense I disagreed with the assumption that this function cannot be done without the ref keyboard. Just put your string in a class. – Marc Roussel Mar 22 '17 at 12:50
  • @MarcRoussel: I think you should carefully re-read the best answer to that question, because IMO you're confusing "reference type" with the way of passing arguments "by reference" or "by value"... – digEmAll Mar 22 '17 at 13:04
  • @digEmAll No I was just saying that it can be done without ref. Sorry for any misunderstanding. By the way the answer is perfectly valid. – Marc Roussel Mar 22 '17 at 14:14
5

One possibly corner-case example: Interlocked.Increment. Without passing the variable by reference, there's no way of performing the increment atomically.

I can't say I've used ref very much myself, to be honest - I generally steer clear of the need to return multiple values, and even then out is usually sufficient. Many of the cases where I've seen ref used, it's been due to the author not understanding how arguments are passed in .NET when it comes to reference types.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I am thining of using for value types of course – Loj Jan 10 '11 at 11:19
  • 1
    @Loj: I don't think there needs to be any "of course" about it - `ref` is still potentially useful for reference types, if you want the caller's argument expression to refer to a different object after the call. – Jon Skeet Jan 10 '11 at 11:23
  • "Many of the cases where I've seen ref used, it's been due to the author not understanding how arguments are passed in .NET when it comes to reference types." Very True Jon!!! – Ashish Jain Sep 24 '13 at 05:55
4

The TryParse methods built into the framework are typical examples. They use out instead of ref but it is the same semantics, it's just that the caller doesn't need to initialize the value. Example:

int result;
bool isSuccess = int.TryParse("some string", out result);
if (isSuccess)
{
    // use the result here
}

As you can see the function returns a boolean indicating whether the operation succeeds but the actual result is returned as out parameter.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1
public static void Main(string args[])
{
    int i=0;
    AddSomething(ref i);
    AddSomething(ref i);
    AddSomething(ref i);
    AddSomething(ref i);


    string mystr = "Hello";
    AddSomeText(ref mystr);
    Console.WriteLine(mystr);


    Console.WriteLine("i = {0}", i);
}


public static void AddSomeText(ref string str)
{
    str+= " World!";
}


public static void AddSomething(ref int ii)
{
    ii+=1;
}
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
0

One of the most common places I see it, is in Save methods of some frameworks.

The reason is that in many cases it is not actually possible to maintain the same object over a save call, if the object is being serialized to another machine and then comes back as a new instance (perhaps with some extra defaults). In that case you need the ref to make it obvious that the original reference is no longer valid.

As for its NECESSITY, I can't come up with an example where it would be required. Most places out is just fine.

Cine
  • 4,255
  • 26
  • 46
0

I think a good example would be trampolining.

This is where you take a recursive function and rework it to a method that is repeatidly called on a set of values. The reason being that instead of going into the stack very deeply the stack remains flat because you return after every call instead of calling yourself.

Regards GJ

gjvdkamp
  • 9,929
  • 3
  • 38
  • 46