Example:
I’d like to have several specialized textboxes that derive from either TextBox or RichTextBox, which both derive from TextBoxBase:
class CommonFeatures<T> : T where T : TextBoxBase
{
// lots of features common to the TextBox and RichTextBox cases, like
protected override void OnTextChanged(TextChangedEventArgs e)
{
//using TextBoxBase properties/methods like SelectAll();
}
}
and then
class SpecializedTB : CommonFeatures<TextBox>
{
// using properties/methods specific to TextBox
protected override void OnTextChanged(TextChangedEventArgs e)
{
... base.OnTextChanged(e);
}
}
and
class SpecializedRTB : CommonFeatures<RichTextBox>
{
// using methods/properties specific to RichTextBox
}
Unfortunately
class CommonFeatures<T> : T where T : TextBoxBase
doesn’t compile (“Cannot derive from ‘T’ because it is a type parameter”).
Is there a good solution to this? Thanks.
C# generics don’t support inheritance from a parameter type.
Do you really need
CommonFeaturesto derive fromTextBoxBase?A simple workaround may be to use aggregation instead of inheritance. So that you would have something like this:
Like @oxilumin says, extension methods may also be a great alternative if you don’t really need
CommonFeaturesto be aTextBoxBase.