I have a confusion that when i pass a variable by refrence in the constructor of another class and after passing that object by refrence i recreate the refrence object with the new keyword.
Now the class in which i have passed the refrenced object dosen’t reflect the updated data.
An exabple of the above problem is shown below:
Object to be passed by Refrence:
public class DummyObject
{
public string Name = "My Name";
public DummyObject()
{ }
}
Class which is passing the Refrence:
public partial class Form1 : Form
{
// Object to be passed as refrence
DummyObject dummyObject = new DummyObject();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// assigning value
dummyObject.Name = "I am Dummy";
// Passing object
Form2 frm = new Form2(ref dummyObject);
frm.Show();
}
private void button2_Click(object sender, EventArgs e)
{
// Displaying Name
MessageBox.Show(this.dummyObject.Name);
}
private void button3_Click(object sender, EventArgs e)
{
// Assigning new object
this.dummyObject = new DummyObject();
// Changing Name Variable
this.dummyObject.Name = "I am Rechanged";
// Displaying Name
MessageBox.Show(this.dummyObject.Name);
}
}
Class to which Object is passed by Reference:
public partial class Form2 : Form
{
private DummyObject dummyObject = null;
public Form2(ref DummyObject DummyObject)
{
InitializeComponent();
this.dummyObject = DummyObject;
this.dummyObject.Name = "I am Changed";
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(this.dummyObject.Name);
}
}
whn i reaasign the object in Form 1 and cdisplay its value in form 2 it still displays “I am Changed” instead of “I am Rechanged”.
How to keep the data synchronized?
You cannot keep variables synchronized in this manner; there is no concept of
refinstance or static variables, onlyrefparameters. ThedummyObjectinstance variable does (and always will) represent a distinct slot of memory. All you’re doing is copying the value from theDummyObjectparameter intodummyObject; you’re doing nothing that would be affected by whether or not the parameter is being declared asref.The typical way is to expose the value of
dummyObjectas a property onForm2.But this means that you’ll need to hold on to your instance of
Form2so that you can change the value of the property.Another option, though somewhat convoluted, would be pass a wrapper class that contains that property, rather than adding it to the form.
You then change your forms to use a
DummyWrapperinstead of aDummyObject, then access thedummyWrapper.DummyObjectproperty when you want to get or set the value. Uas long as you only change the value of theDummyWrapper.DummyObjectproperty and not the actual value of theDummyWrapper, then you’ll be pointing at the same instance.For instance: