I'm wondering if there is a name for the pattern of defining a generic class with one type argument where the type inherits the defining class.

For example

public class A<T> where T : A<T>
{
}

I'm not sure if there even is a name for this. Any help would be much appreciated, thanks.

  • Just out of curiosity, what would be a use case for this? – Flater Aug 10 at 9:37
up vote 4 down vote accepted

Yes, this pattern is called Curiously Recurring Template Pattern (CRTP), at least in C++. Some call it Curiously Recurring Generic Pattern (CRGP) or simply Recurring Generic Types in java. The general language independent term is F-bound polymorphism.

No naming convention for this pattern exists.

  • Keeping an abstract name like T might be fine for very small or very abstract classes.
  • If the type parameter has some meaning in the business domain, consider using that name for clarity. E.g. if your business domain has a Frobnicator concept, you might choose the names class AbstractFrobnicator<Frobnicator>.
  • You could also choose a name that indicates the parameter is a derived class, e.g. Foo<Derived> or Foo<Self>. I'd prefer this over T for larger classes.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.