I would like to ask, if I pass a object to a constructor of a class,the object will be a readonly field of the class,and I modify the property of the object,the property inside the class will also change,I guess it's call by reference.Is there any way to do this better/prevent? thanks
private void Form1_Load(object sender, EventArgs e)
{
Product p = new Product() { Name="New" };
Store s = new Store(p);
p.Name = "MODIFY!";
MessageBox.Show(s.Show());//MODIFY!
}
public class Store
{
private readonly Product product;
public Store(Product product)
{
this.product = product;
}
public string Show()
{
return this.product.Name;
}
}
public class Product
{
public string Name { get; set; }
}
If you don't want
product
inside ofStore
to change if you change the original instance, you have to make a copy before assigning it to the field:Alterantively, you could make
Product
a struct. Structs are always copied when passed to a method, and not passed by reference:What you store in your
readonly
field is a reference. And that reference of course is readonly and never changed. But the content of the referenced object can still be changed.Since
Product
seems to be a data-holding class, one approach might be to simply copy the content into a new instance:Now the content of
Store.product
cannot be changed from outside as long as you don't export this instance.But note that code inside the
Store
class may still be able to change the content.Another option is creating an immutable version of Product:
And now,
Benefits? No one can mess around with
product
insideStore
.