I am using a fictional example for this. Say I have a Widget class, for example:
abstract class Widget { Widget parent; }
Now my other classes will be derived from this Widget class, but suppose I want to put some restriction on the class when defining derived types, so that only the specific "type" of the widget can be the parent of a particular type of Widget.
For example, I got two more widgets from the Widget class, WidgetParent and WidgetChild. By defining a child class, I want to define the type of the parent as WidgetParent, so I do not need to type the parent cast every time I use it.
Exactly what I would like to do is the following:
// This does not works! class Widget<PType>: where PType: Widget { PType parent; } class WidgetParent<Widget> { public void Slap(); } class WidgetChild<WidgetParent> { }
So, when I want to access the parent element of WidgetChild, instead of using it like this:
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();
source share