Should I make this XmlSerializer static?

mafu picture mafu · Jul 16, 2009 · Viewed 7.2k times · Source

I've got a class which uses an XmlSerializer in its Read/WriteXml methods. The Serializer is currently private readonly.

public class Foo : IXmlSerializable
{
    private Bar _bar = new Bar();
    private readonly XmlSerializer serBar = new XmlSerializer (typeof (Bar));

    public void WriteXml (XmlWriter writer)
    {
        serBar.Serialize (writer, Bar);
    }
    // ...
}

I'm considering making the Serializer private static instead, so one instance is shared between all Foos. Is this a good idea, or are there possible issues?

Answer

Pavel Minaev picture Pavel Minaev · Jul 16, 2009

Yes, it is a good idea. No, there aren't any issues with it. In particular, thread safety is not an issue - from MSDN documentation for XmlSerializer class:

Thread Safety

This type is thread safe.