Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing objects and a list of objects by reference in C#
    primarykey
    data
    text
    <p>I have a delegate that modifies an object. I pass an object to the delegate from a calling method, however the calling method does not pick up these changes. The same code works if I pass a <code>List</code> as the object.</p> <p>I thought all objects were passed by reference so any modifications would be reflected in the calling method. Is that correct?</p> <p>I can modify my code to pass a <code>ref</code> object to the delegate. But I am wondering why this is necessary. Or is it?</p> <pre><code>public class Binder { protected delegate int MyBinder&lt;T&gt;(object reader, T myObject); public void BindIt&lt;T&gt;(object reader, T myObject) { //m_binders is a hashtable of binder objects MyBinder&lt;T&gt; binder = m_binders["test"] as MyBinder&lt;T&gt;; int i = binder(reader, myObject); } } public class MyObjectBinder { public MyObjectBinder() { m_delegates["test"] = new MyBinder&lt;MyObject&gt;(BindMyObject); } private int BindMyObject(object reader, MyObject obj) { obj = new MyObject { //update properties }; return 1; } } ///calling method in some other class public void CallingMethod() { MyObject obj = new MyObject(); MyObjectBinder binder = new MyObjectBinder(); binder.BindIt(myReader, obj); //don't worry about myReader //obj should show reflected changes } </code></pre> <p><strong>Update:</strong></p> <p>I am now passing objects by <code>ref</code> to the delegate as I am instantiating a new object inside <code>BindMyObject</code>.</p> <pre><code>protected delegate int MyBinder&lt;T&gt;(object reader, ref T myObject); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload