Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I make this XmlSerializer static?

Tags:

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?

like image 775
mafu Avatar asked Jul 16 '09 07:07

mafu


People also ask

Is XmlSerializer thread safe?

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.

What is the correct way of using XML Deserialization?

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.

Why do we use XmlSerializer class?

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.

Can static class be serialized?

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.


2 Answers

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.

like image 132
Pavel Minaev Avatar answered Oct 06 '22 01:10

Pavel Minaev


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 
like image 34
PROGrand Avatar answered Oct 06 '22 01:10

PROGrand