Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange problem with reference and object cloning
    text
    copied!<p>I have a strange problem with reference and object cloning, which I'm not able to solve. I have a class MyClass which consist of property Name. I also have my custon user control, which have a property of type MyClass - myclassproperty. These controls are placed on form. If I click one of control a new form apperas. I pass one argument to new form - myclassproperty</p> <pre><code>NewForm form = new NewForm(myusercontrol.myclassproperty) this.myclassproperty = myclassproperty; clonedproperty = ObjectCloner.Clone(myclassproperty); </code></pre> <p>clonedproperty is an cloned object. For cloning I use this code, which I found here on stackoverflow</p> <pre><code> public static class ObjectCloner { /// &lt;summary&gt; /// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx /// /// Provides a method for performing a deep copy of an object. /// Binary Serialization is used to perform the copy. /// &lt;/summary&gt; /// &lt;summary&gt; /// Perform a deep Copy of the object. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of object being copied.&lt;/typeparam&gt; /// &lt;param name="source"&gt;The object instance to copy.&lt;/param&gt; /// &lt;returns&gt;The copied object.&lt;/returns&gt; public static T Clone&lt;T&gt;(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } IFormatter formatter = new BinaryFormatter(); Stream stream = new MemoryStream(); using (stream) { formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } } } </code></pre> <p>In new form I have a textbox which is bind to filed Name in object clonedproperty</p> <p>txtName.DataBindings.Add("Text", clonedproperty, "Name");</p> <p>I also have two buttons on my form ''save'' and ''cancel''. If I click cancel, form simply is closed but if I click save I do sth like that</p> <pre><code>this.myclassproperty = clonedproperty </code></pre> <p>and the form is closed.</p> <p>In my opinion, at this moment myusercontrol.myclassproperty is reference to clonedproperty so if I click once again on myusercontrol the new value (which I entered previously) shows.</p> <p>However I have old value all the time :(</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload