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)
{
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
}
UPDATED
I passed objects by ref to the delegate as I was instantiating a new object inside BindMyObject.
protected delegate int MyBinder<T>(object reader, ref T myObject);