Tuesday, January 20, 2009

Serialize using DataContractSerializer

In the past I had couple of posts about serialization - this and this. Recently, came across a need that required to serialize an object that is not public - wanted to serialize an internal class. This could be done using good old reflection techniques but thanks to 3.0/3.5 framework, the solution lies in using DataContractSerializer.

Let's get to the code - quite simple:


using System.Runtime.Serialization;

/// <summary>
/// Serialize using DataContractSerializer
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
internal string Serialize(Object obj)
{
StringBuilder serialXML = new StringBuilder();
DataContractSerializer dcSerializer = new DataContractSerializer(obj.GetType());
using (XmlWriter xWriter = XmlWriter.Create(serialXML))
{
dcSerializer.WriteObject(xWriter, obj);
xWriter.Flush();
return serialXML.ToString();
}
}


Love coding!

2 comments:

Anonymous said...

Thank you very much for posting this. You helped me solve a very tough problem!!

Sam

uTILLIty said...

While DCS is part of WCF, it's abillity to serialize any object (even without DataContractAttribute/DataMemeberAttribute etc) was added in 3.5 SP1, as far as I know!

Tilli