My problem was that I needed a potentially large number of model classes to share a common base. The desired API has a rich set of static factory methods returning new instances. Downcasting a common base class all over the place is ugly, so these factory methods will preferably return the proper type.
In the past, this would have involved generating, either by hand or programmatically, a staggering number of methods. Donkey work. However, with generics, all this shouldn’t be necessary, right?
Now, up until now I have primarily used generics for containers and the like. In such cases the type and the generic class are orthagonal to each other. The type is declared class List and constructed List.
Subclassing and constructing generic types are both forms of specialization. However, since C# lacks mixins, this problem domain calls for both. At first, I didn’t think it would be possible. Then, I thought it would require two related classes, a model class and a factory class. I wanted the model class to have a singleton property referencing its corresponding factory class, but kept running into the same issues that were preventing me from solving the problem in a single class.
Finally, it occurred to me to try subclassing a constructed type while parameterizing the super (generic) type with the subclass: class Foo : Bar.
It works!
Example:
class NActiveRecord<T>
{
static T Find(int id) { ... }
static ListFind(params int[] ids) { ... }
void Save() { ... }
}
class Account : NActiveRecord<Account>
{
...
string Name { get; set; }
...
}
void Main()
{
Account a = Account.Find(1);
Console.WriteLine(a.Name);
a.Name = "New Name";
a.Save();
Listaccounts = Account.Find(1,2,3);
foreach (Account b in accounts)
Console.WriteLine(b.Name);
}