I am using a fictional example for this. Say, I have a Widget class like:
abstract class Widget { Widget parent; }
Now, my other classes would be derived from this Widget class, but suppose I want to put some constraint in the class while defining the derived types such that only a particular ‘type’ of widget can be parent to a particular type of Widget.
For example, I have derived two more widgets from the Widget class, WidgetParent and WidgetChild. While defining the child class, I want to define the type of parent as WidgetParent, so that I dont have to type cast the parent every time I use it.
Precisely, what I would have liked to do is this:
// This does not works! class Widget<PType>: where PType: Widget { PType parent; } class WidgetParent<Widget> { public void Slap(); } class WidgetChild<WidgetParent> { }
So that when I want to access the parent of WidgetChild, instead of using it this way:
WidgetParent wp = wc.parent as WidgetParent; if(wp != null) { wp.Slap(); } else throw FakeParentException();
I want to use it this way(if I could use generics):
wc.parent.Slap();
You should be able to use the code you’ve got by still having the non-generic class
Widgetand makingWidget<T>derive from it:You then need to work out what belongs in the generic class and what belongs in the non-generic… from experience, this can be a tricky balancing act. Expect to go back and forth a fair amount!