views:

52

answers:

1

Possible Duplicate:
Passing By ref and out

C#: does using ref/out for a method parameter make any difference if an object variable is being passed?

In C#, an object variable passes only a reference to the method, which means it is already a ref/out parameter. Is this correct?

+2  A: 

The instance is passed by reference. The pointer to the instance is passed by value, though.

If you use ref, the pointer is passed by reference as well - therefore you can use:

private void CustomDispose(ref object x) { x.Dispose(); x = null; }

CustomDispose(ref someInstance.someField);

someInstance's field will be assigned to null. It might be useful in Disposing via a custom method for example.

Jaroslav Jandek
The instance is not passed by reference, it *is* a reference type.
Lasse V. Karlsen
Lasse V. Karlsen: Well, the instance itself is not passed at all. I just meant that it's like it was being passed by reference. For practical example it's like it's being passed by ref but instead the pointer is passed that contains a reference to the instance. That is why I have also included the pointer in the answer.
Jaroslav Jandek
Yeah, sorry, this question is just a pet peeve of mine, it has come up so many times on SO now that I think we should be able to get the semantics exactly right by now.
Lasse V. Karlsen
@Lasse V. Karlsen: Nothing to be sorry about. You are right that the semantics in my answer are not perfect. I just thought that it is clear enough to understand what exactly goes on there.
Jaroslav Jandek