C# Passing objects and list of objects by reference
Posted
by David Liddle
on Stack Overflow
See other posts from Stack Overflow
or by David Liddle
Published on 2010-06-14T19:15:42Z
Indexed on
2010/06/14
19:22 UTC
Read the original article
Hit count: 156
c#
|pass-by-reference
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
}
© Stack Overflow or respective owner