A new and handy feature of C# 3.0 is "extension methods". Extension methods essentially allow you to write methods for classes that you may or may not have written yourself.
Additionally, a great feature of .NET 2.0 is "generics", which allow you to create templates of methods (and classes) for multiple types at once.
Combine extension methods and generics, and you can really cook up some trouble! In terms of XML serialization, you can code a few simple lines to handle all your XML string serialization needs.
Observe:
public static class Extensions
{
public static string ToXml<T>(this T toSerialize)
{
var serializer = new XmlSerializer(typeof(T));
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
serializer.Serialize(writer, toSerialize);
return sb.ToString();
}
public static T DeserializeXmlString<T>(this string xml)
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(xml))
return (T)serializer.Deserialize(reader);
}
}
Observe. After creating the class above and referencing its namespace in your code, the extension method becomes available for use so that you can perform serialization/deserialization trickery like so:
public class MyClass
{
public int IntProperty { get; set; }
public string StringProperty { get; set; }
}
var mc = new MyClass(){ IntProperty = 1, StringProperty = "Test" };
var xml = mc.ToXml();
//output:
//<MyClass>
// <IntProperty>1</IntProperty>
// <StringProperty>Test</StringProperty>
//</MyClass>
var deserializedMc = xml.DeserializeXmlString<MyClass>();