[.net] C# - Instatiation of Non-Serialized objects during Serialization

Started by
3 comments, last by djz 14 years ago

[Serializable]
public class foo
{
   private int foo;
 [NonSerialized]  
   private byte []bar;

   public foo()
   {
      bar = new byte[128];  // we need to perform this on deserialization too!
   }
}

I have been trying to figure this one out, or at least figure out what google terms to use: basically, I have an object with a buffer that I currently serialize; but the buffer can get quite large, and there's no real reason to serialize it. But it needs to be reset to a new reference on serialization. Currently, if I deserialize my object, I get an exception later on, because bar[] has not been instantiated. I'm sure there must be a simple & elegant way to do this (rather than deserializing, and then looping through all deserialized objects with buffers and reseting them)
Advertisement
What you are after is custom deserialization logic in C#. That search will probably lead you to implement ISerializable.
Thank you!!
You didn't mention which serializer you are using, if it is the Soap- or BinaryFormatter and not the XmlSerializer, the easiest way would be to mark a method with the OnDeserializedAttribute and initialize your buffer there:

[OnDeserialized]internal void InitFields(StreamingContext context) {  bar = new byte[128];}
Quote:Original post by itachi
You didn't mention which serializer you are using, if it is the Soap- or BinaryFormatter and not the XmlSerializer, the easiest way would be to mark a method with the OnDeserializedAttribute and initialize your buffer there:

[OnDeserialized]internal void InitFields(StreamingContext context) {  bar = new byte[128];}


I am using the BinaryFormatter; and this is eventually how I ended up doing it. :)

This topic is closed to new replies.

Advertisement