I’m using the curiously recurring template pattern (CRTP) in my C# project, but I’m having some problems. Code snipped from the link above:
public abstract class Base<T> where T : Base<T>{
public T FluentMethod() {
return (T)(this);
}
}
public class Derived : Base<Derived> {
}
Beautiful! The problem arises when I try to do something like this:
public class SomeClass
{
Base<T> GetItem() { /* Definition */ };
}
SomeClass should be able to return any implementation of the Base class, but of course T has no meaning here as this is in another class. Putting Derived instead of T compiles, but this isn’t what I want, as I should be able to return items of other types too, as long as they derive from Base. Also, GetItem() might return different typed object depending on the state of the SomeClass object, so making SomeClass generic isn’t the solution either.
Am I missing something obvious here, or can’t this be done while using the CRTP?
You must declare the method as generic:
To make it a property you must declare the class itself as generic: