C++ developers are well familiar with the CRTP - Curiously Recurring Template Pattern, where a class can derive from another class, specifying itself as a template parameter.

Every now and then I wish this pattern can be used in C#. If you attempt to implement it C++ style, you would get a compile error:

	public abstract class Base<T> {
		public T FluentMethod() {
			return (T)(this); //error CS0030: Cannot convert type 'InheritanceTest.Base<T>' to 'T'
		}
	}

	public class Derived : Base<Derived> {
	}

This is probably a point at which you give up and find another way of doing things. It is, however, possible to implement a fully functioning curiously recurring class system in C# by simply adding a constraint to the base class like so:

	public abstract class Base<T> where T : Base<T>{
		public T FluentMethod() {
			return (T)(this); 
		}
	}

	public class Derived : Base<Derived> {
	}

If you attempt to read the constraint your brain will probably spin in infinite circles trying to figure out how it is even possible for a type parameter to be the same as the class itself. The fact that it works, however, is not more magic than the C++ version, where the recursive nature of the class declaration simply compiles. What the constraint really says is that *T is a class that derives from Base*, which is what `Derived` is.

Another observation. You cannot use Base<T> by itself. It must be inherited from. The abstract keyword is not compulsory, it will compile without it. You just won’t be able to declare an instance of Base<T> by itself.

This post joins a long list of posts that are inspired by one of my StackOverflow answers. The code that uses this pattern can be found in MVCContrib project.



blog comments powered by Disqus

Published

27 September 2010

Tags