C# Passing objects and list of objects by reference
- by David Liddle
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 pickup these changes. The same code works if I pass a List as the object. I thought all objects were passed by reference so any modifications would be reflected in the calling method?
I can modify my code to pass a ref object to the delegate but am wondering why this is necessary?
public class Binder
{
protected delegate int MyBinder<T>(object reader, T myObject);
public void BindIt<T>(object reader, T myObject)
{
//m_binders is a hashtable of binder objects
MyBinder<T> binder = m_binders["test"] as MyBinder<T>;
int i = binder(reader, myObject);
}
}
public class MyObjectBinder
{
public MyObjectBinder()
{
m_delegates["test"] = new MyBinder<MyObject>(BindMyObject);
}
private int BindMyObject(object reader, MyObject obj)
{
//make changes to obj in here
}
}
///calling method in some other class
public void CallingMethod()
{
MyObject obj = new MyObject();
MyBinder binder = new MyBinder();
binder.BindIt(myReader, obj); //don't worry about myReader
//obj should show reflected changes
}