Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics - trying to find the name of a pattern

I've been trying to find the name of a pattern of generics usage in C#, and I don't know of a better resource than stack overflow!

What I'm doing is creating generic base classes into which the derived class is directly passed - I looked and looked for examples of this or a name for the pattern, and I was hoping one of the great members of this community could help me out.

I did a write up on how it works at http://www.mobiusbay.com/home/alittlesomethingimcallingcascadinggenerics but if you would rather not read it there, an example of it follows:

public abstract class IndexedMemberBase<TDerivedClass> : IDisposable where 
    TDerivedClass : IndexedMemberBase<TDerivedClass>
{
    #region Declarations & Properties
    private static List<TDerivedClass> derivedInstances = new List<TDerivedClass>();
    public static List<TDerivedClass> DerivedInstances
    {
        get { return derivedInstances; }
    }
    #endregion

    #region Constructor(s)
    public IndexedMemberBase()
    {
        if (derivedInstances == null) derivedInstances = new List<TDerivedClass>();
        derivedInstances.Add((TDerivedClass)this);
    }
    #endregion

    #region Methods
    public void Dispose()
    {
        if (derivedInstances.Contains(this) == true)
        {
            derivedInstances.Remove((TDerivedClass)this);
        }
    }
    #endregion
}

That's the base class, and the derived class can be incredibly simple - for example:

public class IndexMember : IndexedMemberBase<IndexMember>
{
    //Add all the crazy business you could ever want!
}

That piece of code throws a pointer to each instance of the dervied class into a static collection for general use - the collection is distinct for each derived class so you won't have conflicts from it existing statically in the base. I find it to be quite useful in my projects, and I hope someone else can find use for it.

The important thing to point out is that the derived class passes itself in the generic signature to the base class.

If anyone has seen this pattern in use, or knows of a name for it - I would really love to see some examples, or at least call it by it's correct name! For now, I'm calling it recursive generics, since it seems to fit, but I'm sure there's a better name!

Thank you very much for your help!

Adam

like image 534
Adam G. Carstensen Avatar asked Feb 25 '23 07:02

Adam G. Carstensen


2 Answers

It's called the Curiously Recurring Template Pattern

(and for some reason it is only very very famous on SO?)

like image 71
sehe Avatar answered Feb 26 '23 19:02

sehe


Eric Lippert has written about this in his blog.

It's called a Curiously Recurring Template Pattern, although that refers to C++ where they are templates and not generics.

like image 24
configurator Avatar answered Feb 26 '23 19:02

configurator