Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a good curiously recurring template pattern (CRTP) in C#

Tags:

c#

crtp

A while back I wanted to create my own data mapper that would be much simpler than your average ORM. In doing so I found the need to have access to the type information of inheriting classes in my base class. My first thought was reflection, but it's too slow (if you use reflection though, check out Fasterflect as it 'almost' eliminates the performance problems of reflection).

So I turned to a solution that I later found out had it's own name: The Curiously Recurring Template Pattern. This mostly solved my problem, but learning how to correctly implement this pattern was a little challenging. The two main questions I had to solve were:

1) How can I let my consuming code work with my generic objects without needing to know the generic parameters the objects were created with?

2) How can I inherit static fields in C#?

The challenging part was actually figuring out the questions. Once I realized what I needed to do, solving these questions was pretty easy. If you find yourself in need of the CRTP, you will likely find yourself needing to answer these questions... they seem to go hand in hand.

like image 842
Brandon Moore Avatar asked Jun 07 '12 21:06

Brandon Moore


People also ask

Why use Curiously Recurring template Pattern?

The CRTP can be used to avoid having to duplicate that function or other similar functions in every derived class.

Is CRTP faster?

CRTP is faster because there is no virtual function call overhead and it compiles to smaller code because no type information is generated.

How CRTP works?

It works because at one point in the cycle you don't need the type to be complete, you only need to know its name. Instantiating Base for Derived does not require Derived to be complete, only to know that it is a class type.

What is CRTP?

A CRT-P is an implantable cardiac resynchronization therapy (CRT) pacemaker for patients with heart failure. The device monitors the heart's rhythm, detects irregularities and corrects them with electrical impulses.


2 Answers

Working with generics without knowing the generic parameter types

When using the CRTP it's good to have a non-generic base class (abstract if possible, but that's not too important) that your 'base' generic class inherits from. Then you can make abstract (or virtual) functions on your non-generic base class and allow consuming code to work with your objects without having to know the generic parameters. For example:

abstract class NonGenBase
{
    public abstract void Foo();
}

class GenBase<T>: NonGenBase
{
    public override void Foo()
    {
        // Do something
    }
}

Now consuming code that has no knowledge of what T is supposed to be can still call the Foo() procedure on your objects by treating them as instances of the base class.

How to solve the static field inheritance problem

When using the CRTP to solve a problem, it's often beneficial to provide access to static fields in inheriting classes. The problem is that C# doesn't allow inheriting classes to have access to those static fields, except through the type name... which often seems to defeat the purpose in this situation. You may not be able to think of a clear example of what I'm talking about and explaining one is beyond the scope of this answer, but the solution is simple so just tuck it away in your knowledgebase and when you find a need for it you'll be glad it's there :)

class GenBase<T>: NonGenBase
{
    static object _someResource;

    protected object SomeResource { get { return _someResource; } }
}

This 'simulates' inheritance of static fields. Keep in mind, however, that static fields on a generic class are not scoped across all your generic implementations. Each generic implementation has its own instance of the static field. If you want a single static field that is available to all the implementations, then you simply need to add it to your non-generic base class.

like image 138
Brandon Moore Avatar answered Oct 19 '22 03:10

Brandon Moore


How can I inherit static fields in C#?

I know it's been a long time since you asked this, but, note that in the .NET 6 Preview, you can put static abstract members on an interface. (IIRC, this feature won't be in the release for .NET 6, it will be in preview status until .NET 7).

So, you can do something like this:

public interface IBoundedCollection
{
    public static abstract int MaximumItemCount { get; }
}

public abstract class BaseCollection
{
    public abstract int Count { get; }
    public abstract int GetMaximumItemCount();

    public abstract BaseCollection CreateUntypedCopy();
}

public abstract class BoundedCollection<TDerived> : BaseCollection
    where TDerived : BoundedCollection<TDerived>, IBoundedCollection
{
    public override int GetMaximumItemCount() => TDerived.MaximumItemCount;


    public abstract TDerived CreateTypedCopy();

    public override BaseCollection CreateUntypedCopy() 
        => CreateTypedCopy();
}

public class LimitTenCollection : BoundedCollection<LimitTenCollection>, IBoundedCollection
{
    public static int MaximumItemCount => 10;

    public override int Count { get; }

    public override LimitTenCollection CreateTypedCopy() => new LimitTenCollection();
}

Note the following:

  • You can work with BaseCollection without working with type arguments. For example, you can use Count, GetMaximumItemCount(), and CreateUntypedCopy().
  • BoundedCollection<TDerived> can provide the implementation for MaximumItemCount since TDerived is constrained to IBoundedCollection
like image 1
Mike Christiansen Avatar answered Oct 19 '22 04:10

Mike Christiansen