EnriqueMark
Design Patterns & Architecture

CRTP

2026-03 English

CRTP is a pretty interesting thing. The full name is generic base class, and the acronym stands for Curiously Recurring Template Pattern. It’s a base class that constrains the input type of the subclass.

public abstract class JobBase<TJob> : IJobDefinition
   where TJob : JobBase<TJob>

What this means is, implement interface I, but with a constraint, the generic TJob has to inherit from the class after the :. See Inheritance and type constraints for details.

A base class like this is normally for when an internal method needs an outside type to build its logic, and that type is only known at implementation time. Then you need CRTP. The base class requires the subclass to pass its own type in, otherwise the base class can’t work properly.

We usually say “composition over inheritance”, but when there’s a lot of reuse and the internal logic depends on a type that only comes in at implementation time, CRTP is what works best. With composition you’d have to rewrite it at every implementation, which costs you instead.

Composition fits best for the cases where you’d write inheritance purely for reuse. There composition is the better call, because the constraint isn’t strong, and decoupling has no need for an inheritance pattern that might couple things again.

Next is lifecycle management. With composition it goes in the DI container, with inheritance it’s usually the base class upstream.


Translation note. I wrote this in Chinese. This English version is an LLM translation, so the wording is not mine even though the thinking is. Original: CRTP.