This was touched on above, but apparently, those that responded didn't get it, and I don't yet seem to have the points here to respond to the original post. So here goes:
I'd like to have an implicit (or at least enforceable) TSelf
type for generic classes. Consider:
public class GenericWithFactory<TSelf, T> {
public static TSelf Create(T parameter) {
TSelf ret = default(TSelf);
// initialize the object...
return ret;
}
}
Currently, in order to support a whole host of instance-type constructs, such as a factory method (Create(T parameter)
in this case), you have to pass the class you're declaring as a type parameter:
public class GwfOfSomething : GenericWithFactory<GwfOfSomething, Something> {
// ...
}
You're thus forced to repeat the name of your instance class before you've even got to the opening brace! Also, there's no sure-fire way to enforce that TSelf
must always be the class that's being declared. Thus, you can't reliably stop the user from doing this:
public class GwfOfSomethingElse : GenericWithFactory<GwfOfSomething, SomethingElse> {
// ...
}
So, from the base class, how do we generically access the type of the instance class? Syntactically, the cleanest approach would be to overload this
, using it in a specialized where
clause in the base class declaration:
public class GenericWithFactory<TSelf, T>
where TSelf: this
{ /* ... */ }
Since the instance declaration can thus only ever have one value for TSelf
, it can simply be elided in practice:
public class GwfOfSomething: GenericWithFactory<Something> {
// ...
}
Whether this last is a good idea, and whether the actual TSelf
type parameter is available in the subclass' scope is a subject for further debate. But at least we have a cleaner way of keeping track of instance types from generic bases.