I understand that I can't extend static classes in C#, I don't really understand the reason why, but I do understand that it can't be done.
So, with that in mind, here is what I wanted to achieve:
public static class GenericXmlSerialisationExtender
{
public static void WriteToXML<T>(this T targetObject, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StreamWriter(fileName, false, Encoding.UTF8))
{
serializer.Serialize(writer, targetObject);
}
}
public static T ReadFromXML<T>(string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(fileName, Encoding.UTF8))
{
return (T)serializer.Deserialize(reader);
}
}
}
I.e. I wanted to define .WriteToXML for instances (there are quite a lot of config / static data classes which I need to use which just use vanilla XML Serialization), and then .ReadFromXML for types.
So effectively I could call something like:
MyType typeInstance = MyType.ReadFromXML(path_to_data);
What would be the 'proper' way of encapsulating that? I once worked with a colleague who believed 'code re-use' was copy & paste, and I'd rather not put myself in that bracket!