Static Generic Class

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?

Print | posted on Wednesday, October 05, 2005 2:26 PM

Feedback


Gravatar

#  10/6/2005 7:48 AM Tomer Gabel

Static method inheritence makes no sense due to the simple fact that you don't have an object instance with a vtable to index into (the same reason you don't have static methods in 1.1, generic or otherwise).

However, I'm not quite sure why your second example wouldn't work; I've never worked with generics, but usually if you have a static method X of class A, if class B inherited from class A you could call B.X just fine (this would in practice result in A.X but it is syntactically alright).


Gravatar

#  10/7/2005 3:39 PM Ayende Rahien

Thank you for the information, I posted a correction here:
http://www.ayende.com/Blog/2005/10/07/CorrentingMyMistakeStaticMethodsChildClasses.aspx


Gravatar

# Correnting My Mistake: Static Methods & Child Classes 2/3/2007 7:49 AM www.ayende.com

Comments have been closed on this topic.