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!
You would define it in exactly the way you have done already, but to call it you would use a standard static method call:
(You might want to give your GenericXmlSerialisationExtender class a more appropriate name if you do this, or move it to a different static class)
The reason that extension methods can’t work on Static methods, is that there is no object to attach the extension method too.
In your example:
Nowhere in that line have you defined the type that you would like to extend. Extension methods require that the first parameter be an object that you would like the extension method to act upon.
Extension methods are just syntactic sugar, as a nice way of creating a static helper method.
in .net 2.0 you would write:
.net 3.5 gives you the ability to do this:
So when you want to do something outside the scope of the handy extension methods, you just fall back to the older static helper method pattern.