Higher Kinded Types in C# Part 2 — Homogenous invoice

This is the second part of the Higher Kinded Types in C# series. For your convenience you can find other parts in the table of contents in Part 1 — Introduction

So now we can use invoice with items as Brand< Started, string>. However, what we really want to use is Started< string>. How can we do that?

We need to use some magic to seamlessly translate Started< string> into Brand< Started, string>. Notice that there are two different Started types here: one is generic, one is not. And they are completely unrelated when it comes to class hierarchy.

Let’s start with this:

So we store the target of this object (which is our Started< string> instance). We also have some helper methods to translate to and from higher kinded type.

We need this:

So we have some provider of real object casted to correct type. We go with dynamic just to make it simpler when it comes to type casting since .NET doesn’t support overriding method with covariant return type so we’d need to cast it on the caller side (which we want to avoid).

Now, markers:

So we just cast the type correctly.

Now we process invoice in this way:

To finish an item we do this:

So we reuse Finish method which we used last time. That method worked on normal generic typ, now we reuse it to work on our flattened higher kinded type.

Let’s now create invoice and run the magic:

Crucial parts here are:


This way we can transform items from one to the other.

This handles homogenous items. Next time we will see how to have items of different types.