Note that there are some explanatory texts on larger screens.

plurals
  1. POMultiply serialization of same object in C#
    text
    copied!<p>Is it possible to prevent multiply serialization of same object in C#? It looks like for each Serialize call on object it's produce new instance. Is it right behaviour? Or maybe I'm doing something wrong? I've coded small example that shows what i'm mean.</p> <pre><code>static void Main(string[] args) { if (File.Exists("test.bin")) { Stream stream = File.Open("test.bin", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Publisher pub_result = (Publisher)formatter.Deserialize(stream); Subscriber sub_result = (Subscriber)formatter.Deserialize(stream);//this produce second instance of Subscriber //this two calls prints different hashcodes pub_result.BroadcastEvent(); sub_result.on_event_recieve(); } else { Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); pub.on_event_publish += sub.on_event_recieve; pub.BroadcastEvent(); Stream stream = File.Create("test.bin"); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, pub);//sub serialized here too because publisher delegate contains reference to it formatter.Serialize(stream, sub);//serialize it again. } Console.Read(); } </code></pre> <p>Subscriber class</p> <pre><code>[Serializable] public class Subscriber : ISerializable { public Subscriber(SerializationInfo info, StreamingContext context) { } public void on_event_recieve() { Console.Write("Event Recieved on object " + this); } public void GetObjectData(SerializationInfo info, StreamingContext context) { } public override string ToString() { return GetHashCode().ToString(); } } </code></pre> <p>Publisher class</p> <pre><code>[Serializable] public class Publisher : ISerializable { public delegate void on_event_publish_delegate(); public on_event_publish_delegate on_event_publish; public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("delegate", on_event_publish, typeof(on_event_publish_delegate)); } public Publisher(SerializationInfo info, StreamingContext context) { on_event_publish = (on_event_publish_delegate)info.GetValue("delegate", typeof(on_event_publish_delegate)); } public void BroadcastEvent() { on_event_publish(); } public override string ToString() { return GetHashCode().ToString(); } } </code></pre>
 

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