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?
Since XmlSerializer is one of the few thread safe classes in the framework you really only need a single instance of each serializer even in a multithreaded application. The only thing left for you to do, is to devise a way to always retrieve the same instance.
The most common usage of XML serialization is when XML data is sent from the database server to the client. Implicit serialization is the preferred method in most cases because it is simpler to code, and sending XML data to the client allows the Db2 client to handle the XML data properly.
XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.
In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.
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.
According to Neal - even more universal and safe through Generics and readonly:
public static class Helper<T> { public static readonly XmlSerializer Serializer = new XmlSerializer(typeof(T)); }
Use as:
Helper<My>.Serializer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With