Note that there are some explanatory texts on larger screens.

plurals
  1. POReference to the Main Form whilst trying to Serialize objects in C#
    text
    copied!<p>I have a button on my main form which calls a method to serialize some objects to disk. I am trying to add these objects to an ArrayList and then serialize them using a BinaryFormatter and a FileStream. </p> <pre><code> public void SerializeGAToDisk(string GenAlgName) { // Let's make a list that includes all the objects we // need to store a GA instance ArrayList GAContents = new ArrayList(); // Structure and info for a GA GAContents.Add(GenAlgInstances[GenAlgName]); // There may be several running GA's GAContents.Add(RunningGAs[GenAlgName]); using (FileStream fStream = new FileStream(GenAlgName + ".ga", FileMode.Create, FileAccess.Write, FileShare.None)) { BinaryFormatter binFormat = new BinaryFormatter(); binFormat.Serialize(fStream, GAContents); } } </code></pre> <p>When running the above code I get the following exception:</p> <p>System.Runtime.Serialization.SerializationException was unhandled Message=Type 'WindowsFormsApplication1.Form1' in Assembly 'GeneticAlgApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.</p> <p><strong>So that means that somewhere in the objects I'm trying to save there must be a reference to the main form. The only possible references I can see are 3 delegates which all point to methods in the main form code. Do delegates get serialized as well? I can't seem to apply the <code>[NonSerialized]</code> attribute to them.</strong> </p> <p>Is there anything else I might be missing? Even better, is there a quick method to find the reference(s) that are causing the problem?</p> <p><strong>UPDATE:</strong> </p> <p>Well I got my code to work by saving the delegates into temporary variables and then setting them to null before serialization. I then set them back to the original values afterwards. It seems like there should be a better way to do this. Any comments please?</p> <p><strong>ANSWER:</strong></p> <p>I couldn't figure out a way to stop my delegates from being serialized other than setting them to null before serializing, however I think the best solution was to <strong>change my code to use events instead</strong>. As Mark Gravell stated in his answer events can be omitted from serialization by marking them with the <code>[field:Nonserialized]</code> attribute. Problem solved. Nobody actually suggested this but I guess Mark's answer was the closest.</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