Static Generic Class

time to read 4 min | 744 words

Now this is a cool feature I just discovered. I don't think that this is the true name, but it describe what it does. I'm currently trying to give ActiveRecord a more .Net 2.0 interface, and I'm currently concentrating on the static methods of the ActiveRecordBase class. The current best practice for ActiveRecord is to create a type safe wrapper on your class when you're inheriting from ActiveRecordBase. The reasoning is very simple:

  1. Blog []blogs = Blog.FindAll();
  2. Blog []blogs = (Blog[]) ActiverRecordBase.FindAll(typeof(Blog));

I'm pretty sure that you would want to use the first line than the second one and this is the best way to get this in .Net 1.1. The problem is that you need to duplicate the delegating code per each class (Blog.FindAll() merely calls the second line.

What I want is inherited static methods. That would be the ideal solution for this kind of problem:

public class ActiveRecordBase<T> where T : ActiveRecordBase
   public static T[] FindAll() { .... }

public class Blog : ActiveRecordBase<Blog> { ... }

Blog [] blogs = Blog.FindAll();

The compiler would check the Blog class for a static FindAll method, and then its base, and so on.

Since we don't have that, I turned to another route: The Repository. At first I considered calling it ActiveRepository, but that is really bad taste in my opinion. Anyway, the point of this post is that I started writing it like this:

public static class Repository
   public static T[] FindAll<T> () where T : ActiveRecordBase {}

Blog [] blogs = Repository.FindAll<Blog>();

It didn't feel quite right to me, so I thought to try another way, but I was certain that it wouldn't work:

public static class Repository<T> where T : ActiveRecordBase
   public static T[] FindAll<T> ()x{}

Blog [] blogs = Repository<Blog>.FindAll();

It works! And the syntax is far more natural this way.

What do you think?