C# objects by Ref

后端 未结 8 798
清歌不尽
清歌不尽 2021-01-27 12:23

If one passes an object to a method using the \'Ref\' keyword then what is the difference with passing it without the ref keyword?

Because both yield the same result, th

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 12:51

    When you pass an object to a method using the ref key word, the called method can update the reference itself, not only the object. That means that in the following code snippet:

    object a = new object();
    SomeMethod(ref a);
    

    ...a may be another object instance after the call than it was before the call. If you pass an object without the ref keyword, the called method can update properties and members of the passed object, but cannot replace the object itself with another instance.

提交回复
热议问题