I was writing some unit tests the other day and wanted a way to compare an entire object for a test assertion. I also wanted to be able to hand write an object and then use it to compare a result in a test. I immediately thought of XML serialization in .Net and started writing the code.

Unfortunately, it was then that I realized that the XML Serializer has a few limitations. First of all, you must have a default constructor declared for all of your classes. Now I normally use this convention (especially with the C# 3.0 initialization features), but there were several classes I didn’t write in the project I am working on.

The second limitation had to do with properties in a class that were declared as interfaces (e.g. IList<T>). I don’t know why Microsoft didn’t include this as part of the serializer, but it is definitely missing.

I started thinking about WCF and serialization across the wire and realized this problem had to have been solved by the DataContractSerializer or people would be irate. So I created some code to use the DataContractSerializer instead. The code looked like this:

DataContractSerializer oDcs =
new DataContractSerializer(typeof(TypeToBeSerialized));
XmlWriterSettings settings =
new XmlWriterSettings() { Indent = true };
using (XmlWriter w = XmlWriter.Create(fileName, settings))
{
    oDcs.WriteObject(w, list);
}

That worked quite well.

Copyright © Scott P. Rudy 2009 All Rights Reserved
Advertisements