C #: is ref / out used for a method parameter if any object variable is passed?

Possible duplicate:
Passing through ref and out

C #: is ref / out used for a method parameter if any object variable is passed?

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

+4
source share
2 answers

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

If you use ref , the pointer is also passed by reference - so you can use:

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

someInstance field will be set to null. This can be useful in Disposing using a custom method, for example.

+2
source

To confirm the first part of your question:

  • when working with an object (instance) in .NET, you always deal with two objects: an actual, anonymous object and a named reference to this object. This link is a field, variable, or parameter.

  • You cannot pass an instance of an object as a parameter at all, you can only pass a link.

  • You can pass the link by link, which means that you can specify it elsewhere

 void SetNull(ref MyObject parameter) { parameter = null; // would make no sense w/o the ref } 
+1
source

All Articles