6

someone in my team stumbled upon a peculiar use of the ref keyword on a reference type

class A { /* ... */ } 

class B
{    
    public void DoSomething(ref A myObject)
    {
       // ...
    }
}

Is there any reason someone sane would do such a thing? I can't find a use for this in C#

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Luk
  • 5,371
  • 4
  • 40
  • 55

4 Answers4

16

Only if they want to change the reference to the object passed in as myObject to a different one.

public void DoSomething(ref A myObject)
{
   myObject = new A(); // The object in the calling function is now the new one 
}

Chances are this is not what they want to do and ref is not needed.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
13

Let

class A
{
    public string Blah { get; set; }
}

void Do (ref A a)
{
    a = new A { Blah = "Bar" };
}

then

A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (ref a);
Console.WriteLine(a.Blah); // Bar

But if just

void Do (A a)
{
    a = new A { Blah = "Bar" };
}

then

A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (a);
Console.WriteLine(a.Blah); // Foo
abatishchev
  • 98,240
  • 88
  • 296
  • 433
0

The ref keyword is usefull if the method is supposed to change the reference stored in the variable passed to the method. If you do not use ref you can not change the reference only changes the object itself will be visible outside the method.

this.DoSomething(myObject);
// myObject will always point to the same instance here

this.DoSomething(ref myObject);
// myObject could potentially point to a completely new instance here
bitbonk
  • 48,890
  • 37
  • 186
  • 278
0

There's nothing peculiar with this. You reference variables if you want to return several values from a method or just don't want to reassign the return value to the object you've passed in as an argument.

Like this:

int bar = 4;
foo(ref bar);

instead of:

int bar = 4;
bar = foo(bar);

Or if you want to retrieve several values:

int bar = 0;
string foobar = "";
foo(ref bar, ref foobar);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
peterthegreat
  • 406
  • 3
  • 9