3

What is the difference between

public function Foo(ref Bar bar)
{
   bar.Prop = 1;
}

public function Foo(Bar bar)
{
   bar.Prop = 1;
}

essentially what is the point of "ref". isn't an object always by reference?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
leora
  • 188,729
  • 360
  • 878
  • 1,366

2 Answers2

10

The point is that you never actually pass an object. You pass a reference - and the argument itself can be passed by reference or value. They behave differently if you change the parameter value itself, e.g. setting it to null or to a different reference. With ref this change affects the caller's variable; without ref it was only a copy of the value which was passed, so the caller doesn't see any change to their variable.

See my article on argument passing for more details.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I guess you mean "the argumetn itself can be passed by reference or value" and not "by parameter or value". Or is my vocabulary wrong? – erikkallen Apr 08 '09 at 11:22
9

Yes. But if you were to do this:

public function Foo(ref Bar bar)
{
   bar = new Bar();
}

public function Foo(Bar bar)
{
    bar = new Bar();
}

then you'd see the difference. The first passes a reference to the reference, and so in this case bar gets changed to your new object. In the second, it doesn't.

David M
  • 71,481
  • 13
  • 158
  • 186