a bit confused with out and ref keywords

  • Thread starter Thread starter Flip
  • Start date Start date
F

Flip

Maybe I'm reading too much, I'm sorry if this is a very newbie question.

I'm reading the OReilly's Programming C# book, and it talks about ref and
out, cool. I thought I understood you have out on the outgoing and ref on
the accepting method side. But now I'm reading a webpage from another
posting (http://www.yoda.arachsys.com/csharp/parameters.html), that has the
out (or ref) on the method call and on the method declaration. HUH? I
thought I understood it before, now I think I understand it better (from the
webpage), but there is still use use case of mixing the out and ref
together. Can anyone clear up this confusion? Thanks.
 
Flip said:
Maybe I'm reading too much, I'm sorry if this is a very newbie question.

I'm reading the OReilly's Programming C# book, and it talks about ref and
out, cool. I thought I understood you have out on the outgoing and ref on
the accepting method side.

No. They're different modifiers.
But now I'm reading a webpage from another
posting (http://www.yoda.arachsys.com/csharp/parameters.html), that has the
out (or ref) on the method call and on the method declaration.

Yes. You need to specify it on both the call and the declaration, and
they must be the same in both places.
HUH? I thought I understood it before, now I think I understand it
better (from the webpage), but there is still use use case of mixing
the out and ref together. Can anyone clear up this confusion? Thanks.

Out and ref are different modifiers. They're very similar - the
differences are in terms of "definite assignment". I'm not sure I can
spell the differences out better than I did on the page:
http://www.yoda.arachsys.com/csharp/parameters.html#out

If the O'Reilly book really says you need out in one place and ref in
the other, it's talking rubbish.
 
Hi Flip,

Use "out" (output) paramater if you want to set its value in
method's body, e.g.:

void GetLocation(out int x, out int y, Point p) {
x=p.X;
y=p.Y;
}

Use "ref" (reference) parameter if you want to get and set its
value in method's body, e.g.:

void Increment(ref int i, int step) {
i=(i+step);
}

HTH

Marcin
 
Back
Top