The self referencing generic

Every now and then you stumble upon a feature that you didn’t know existed, and sometimes even thought couldn’t exist. This happened to me when I was working on my implementation of the ActiveRecord pattern for .NET. Main main goal was to provide an easy way to get strongly typed data from a database “more or less” effortless. I wanted to implement it using inheritance so that the final classes would end up having all of the appropriate access methods without having to implement any interfaces, but soon realized that this would mean that the base class would have to return its data as its super class type.

That’s when I met the “self referencing generic” :)

In .NET (and Java) it’s possible to let a class inherit a generic and provide itself as the type parameter without causing any circular errors. This of course opens the door to some seriously bad circular programming, but also to some nifty features. With this feature, I could now create a base class that could contain the following method.

public abstract class ActiveRecord<T> : IDisposable
{
    public static List<T> Get(string where, params object[] args) {
        ...
    }
} 

I could then also declare my ActiveRecord like this, which would give me access to just the functionality i desired.

public class MyRecord : ActiveRecord<MyRecord> { ... }

List<MyRecord> records = MyRecord.Get("myfield = @0", "myvalue") ; 

And that’s good stuff :) If you want to look closer at the full implementation the source code is available at my GitHub project TidyUI.Data.

No Comments

Start the ball rolling by posting a comment on this article!

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>