I was recently interested in getting C# objects to serialize into XML so that I could save and load a configuration out of a file. Sadly, C# support for XML and serialization is far from the best stuff I've seen in programming. But anyway, here's what this post is about: using DataContract with a bit of extension magic to get anything to be serializable into XML!

One small problem when you use the Serializable attribute of C# is that you cannot serialize dictionary directly and we all know dictionaries are a VERY useful structure to have serialized. One easy way to have serializable dictionaries is to use the DataContract attribute instead. It implies a bit more code compared to the version where you use the Serializable attribute, but not that much more (mostly the WriteObject and ReadObject lines).

I haven't coded any of this, so thanks to user Loudenvier from Stackoverflow.com! This solution allows you to turn ANY object into an XML string representation. It also allows you to turn that string back into an object representation. Very useful.


public static class SerializationExtensions
{
    public static string Serialize<T>(this T obj)
    {
        var serializer = new DataContractSerializer(obj.GetType());
        using (var writer = new StringWriter())
        using (var stm = new XmlTextWriter(writer))
        {
            serializer.WriteObject(stm, obj);
            return writer.ToString();
        }
    }
    public static T Deserialize<T>(this string serialized)
    {
        var serializer = new DataContractSerializer(typeof(T));
        using (var reader = new StringReader(serialized))
        using (var stm = new XmlTextReader(reader))
        {
            return (T)serializer.ReadObject(stm);
        }
    }
}

How to use example


// dictionary to serialize to string
Dictionary<string, object> myDict = new Dictionary<string, object>();
// add items to the dictionary...
myDict.Add(...);
// serialization is straight-forward
string serialized = myDict.Serialize();
...
// deserialization is just as simple
Dictionary<string, object> myDictCopy = serialized.Deserialize<Dictionary<string,object>>();

Source: http://www.stackoverflow.com

I've just stumbled upon a series of articles from Richard Fine that were written in 2003 which describes the basics of a game engine he calls Enginuity. It lays the foundations to basic memory management, logging, kernel and tasks management and much more. An extremely interesting read. Sadly, you can read in the articles that this was projected to be a series of more than 8 articles, but it seems it stopped at the fifth article. If anyone knows where to find the rest (if it exists), I'd be grateful!

On GameDev.net: Part 1 Part 2 Part 3 Part 4 Part 5