Here’s a handy Extension Method in C# that attaches a “ToXml()” method to any and all object instances.  I added the capability to dictate whether or not to use the classic XmlSerializer or the DataContractSerializer that came to us with WCF.  I made the XmlSerializer the default because typically, when I’m doing this programmatically in my code, it’s intended for human eyes and the XmlSerializer is far more readable, but the DataContractSerializer is what’s actually used at runtime by WCF.  So, call the overload the matters to you.

        public static string ToXml<T>(this T obj) where T : class
        {
            return ToXml(obj, false);
        }

        public static string ToXml<T>(this T obj, bool useDataContractSerializer) where T : class
        {
            if (obj != null)
            {
                Type type = typeof (T);

                Action<XmlWriter, object> action;
                
                if (useDataContractSerializer)
                {
                    action = new DataContractSerializer(type).WriteObject;
                }
                else
                {
                    action = new XmlSerializer(type).Serialize;
                }


                using (MemoryStream stream = new MemoryStream())
                {
                    XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.UTF8, Indent = true };
                    XmlWriter writer = XmlWriter.Create(stream, settings);

                    if (writer != null)
                    {
                        byte[] bytes;

                        using (writer)
                        {
                            action(writer, obj);
                            writer.Flush();
                            stream.Flush();

                            bytes = stream.ToArray();
                        }

                        return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    }
                }
            }

            return null;
        }

 

This is a good example of C# generics using Action<T>.  Notice I’m assigning the variable “action” to either the XmlSerializer’s Serialize() method, or the DataContractSerializer’s WriteObject() – which both have a method overload of void (XmlWriter writer, object obj).  I really like this syntax as it provides yet another way to remove duplication from your code without requiring the types to share a base class or interface, and without having to create a full blown Template Method pattern implementation.

And it works in Silverlight too :)