Friday, August 25, 2006

Serialization in .NET

I had a Java example to work from, but had to do this in .NET. In this case, my class basically had a Hashtable that I wanted to serialize. On the Java side, there really isn't much more to this than creating an ObjectOutputStream and then calling writeObject(this). If you add implements Serializable and add a couple UIDs, you're all set. Actually very easy.

Well, not so much on the C# side. First, you class needs to have the [Serializable()] attribute set and you also implement ISerializable. All fine so far, but implementing this interface means you need a GetObjectData method too. Visual Studio drops the skeleton in your class, but that's were my general clue of what I was doing stopped.

Instead of going through all the crap I went through, in the end you need to simply add a couple lines in GetObjectData to add whatever local variables you want to serialize. In this case, it was just that Hashtable, so my method looks like:
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("hashSeries", hashSeries);
}

So that's all and fine -- but you need to realize now that you've only got a way to get the data serialized. The part they don't really tell you is that now you need a special ctor for your serializable class that's used when you call Deserialize on the input stream and cast it back to your original object. This constructor needs the same parameters as that GetObjectData method and basically just does things in reverse:
protected StockDatabase(SerializationInfo info, StreamingContext context)
{
hashSeries = (Hashtable)info.GetValue("hashSeries", typeof(Hashtable));
}
Simple as pie right? I really didn't spin my wheels too long on this one, but I did do some real research trying to find a good example and piece together the bits from the various things I saw on the way to something that works. The best example ended up being the one for the Deserialize Method even though it doesn't serialize a class object.

No comments: