Blog of Rob Galanakis (@robgalanakis)

Generic Interfaces/Abstract Base Classes

I want to show a really useful pattern I’ve been taking advantage of recently.

public interface IXElementSerializable
	where T : IXElementSerializable
{
	T Deserialize(XElement element);
	XElement Serialize();
}

public class MyType : IXElementSerializable
{
	public MyType Deserialize(XElement element)
	{
		…
	}
	public XElement Serialize()
	{
		…
	}
}

I find it super useful, as you can return the type itself in the interface/implementation, rather than the interface type. Using the generic constraint also makes it clear how to use the interface. You can also use it on abstract methods/properties on abstract base classes, that you want to return the subtype. That’s all there is to it.

Leave a Reply