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.)
That's a funny Curiously Recurring Template Pattern, isn't it?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With