Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# unusual inheritance syntax w/ generics

I happened upon this in an NHibernate class definition:

public class SQLiteConfiguration : PersistenceConfiguration<SQLiteConfiguration>

So this class inherits from a base class that is parameterized by... the derived class?   My head just exploded.

Can someone explain what this means and how this pattern is useful?

(This is NOT an NHibernate-specific question, by the way.)

like image 845
anon Avatar asked Jan 08 '11 03:01

anon


2 Answers

That's a funny Curiously Recurring Template Pattern, isn't it?

like image 55
user541686 Avatar answered Oct 19 '22 06:10

user541686


I have used the same pattern when developing a double linked tree. Each node has 1 parent, and 0-many children

class Tree<T> where T : Tree<T>
{
    T parent;
    List<T> children;
    T Parent { get; set; }
    protected Tree(T parent) 
    {
        this.parent = parent; 
        parent.children.Add(this);
    }
    // lots more code handling tree list stuff
}

implementation

class Coordinate : Tree<Coordinate>
{
    Coordinate(Coordinate parent) : this(parent) { }
    static readonly Coordinate Root = new Coordinate(null);
    // lots more code handling coordinate systems
}

usage

Coordinate A = Coordinate.Root;
Coordinate B = new Coordinate(A);

B.Parent // returns a Coordinate type instead of a Node<>.

So anything that inherits from Tree<> will contain properties for parent and children objects in the appropriate type. This trick is pure magic for me.

like image 29
John Alexiou Avatar answered Oct 19 '22 06:10

John Alexiou