I have some classes inherit from existing Windows Controls like TextBox and DateTimePicker, ..etc
I want to add custom functionalities for these classes like (Read, Alert, …etc)
these added functionalities are the same in all these classes
The problem is: these classes inherited from difference parents so I can’t put my added functionalities in the parent class,
What’s the best practice in this case:
-
repeat the code in each inherited
class -
Use a separated class have the
functionalities as Static Methods
with parameter from an interface, implement this interface for the classes and
then pass them. -
Use a separated class like the second approach but with Dynamic parameter (which added in C# 4.0)
or other !!
Thanks in advance
I’d consider option 4: composition.
First, define your set of functionality. We’ll assume that your partial list is exclusive, so “Read” and “Alert.”
Second, create a single class that implements this functionality, something like
MyCommonControlBehaviors. I’d prefer this implementation not be static if possible, though, it may be generic.Third, use composition to add an instance of this class to each of your custom control types and expose that functionality through your custom control:
Depending on specifics, you can get creative to the degree necessary. E.g., perhaps your custom behaviors need to interact with private control data. In that case, make your control implement a common
ICommonBehaviorHostinterface that your common behaviors need. Then pass the control into the behavior class on construction as an instance ofICommonBehaviorHost: