Serialization is one of my favorite features of .Net and I use it more every day. Much like Xml, once you've gotten the hang of it, you find new uses every time you turn around.
Today I wanted to serialize to string. Simple enough? The examples I found online often created byteArrays and char arrays and went through more work than necesary. So, for those who are searching like I was, here is the simplest example I could write.
The simplest overload provided by the Serialize method of the System.Xml.Serialization.XmlSerializer class takes two parameters: TextWriter and an instance of the class to serialize.
System.IO.StringWriter inherits from TextWriter, therefore, it can be used in this method call.
using System;
using System.Xml.Serialization;
using System.IO;
namespace HPCi.ResourceGuide.Google
{
[Serializable]
///
/// A very simple entity class
public class Class1
/// A couple of public fields.
/// In the real world, I always create
/// private fields with public accessors
/// additionally, I usually initialize fields to
/// default values or empty values rather than null
public string MyPublicStringField = String.Empty;
public bool IsPrettyCool = true;
/// Serialization of the class
/// Incredibly simple and can be used for any class,
/// just change the type
/// string
public string SerializeToXml()
// Serialization of Class into string of xml
XmlSerializer xmlsSlzr = new XmlSerializer( typeof( Class1 ) );
StringWriter sw = new StringWriter();
xmlsSlzr.Serialize( sw, this );
return sw.ToString();
}
note: you could easily make this a static method and pass in the class instance to serialize. Use reflection to create a type to pass to the XmlSerializer contructor.
The following code illustrates this:
public static string SerializeToXml(object obj)
// Serialization of generic Class into string of xml
XmlSerializer xmlsSlzr = new XmlSerializer( obj.GetType() );
xmlsSlzr.Serialize( sw, obj);
I don't like this approach as much as it reminds me too much of vb and utility function libraries. A less oo approach.