开发者

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

This question already has an answer here: Closed 12 years ago.

Possible Duplica开发者_JAVA技巧te:

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?


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.


To confirm the first part of your question:

  • when dealing with an object (instance) in .NET, you always deal with 2 entities: the actual, anonymous object and the named reference to that object. That reference is a field, variable or parameter.

  • You cannot pass the object instance as a parameter at all, you can only pass the reference.

  • You can pass a reference by reference, meaning you can make it point somewhere else

 

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜