I've found myself in need of something like this:
// This could just as well be a concrete class.
//
// It is an interface for the sake of this example.
public interface Quark
{
void Do();
}
public class Strange : Quark
{
public virtual void Do()
{
// Something is done
}
public void DoSpecificThing()
{
MessageBox.Show("Specific Thing!");
}
}
public class Charm : Quark
{
public virtual void Do()
{
// Something else is done
}
public void DoAnotherSpecificThing()
{
MessageBox.Show("Another Specific Thing!");
}
}
In another file:
internal class ReUsableCode<BaseType> : BaseType // <- not allowed
{
public override void Do()
{
// Let's pretend this is around 2000 lines of
// 90's-style Win32 message spaghetti.
MessageBox.Show(base.GetType().ToString() + " did!");
base.Do();
}
}
public class LibraryStrange : ReUsableCode<Strange>
{
}
public class LibraryCharm : ReUsableCode<Charm>
{
}
In a function somewhere:
LibraryStrange imStrange = new LibraryStrange();
LibraryCharm imCharmed = new LibraryCharm();
imStrange.Do();
imStrange.DoSpecificThing();
imCharmed.Do();
imCharmed.DoAnotherSpecificThing();
In C++, I'd just make a template that does precisely the above.
This isn't possible in C#, for the reason above, and that multiple-inheritance is also disallowed. So, how might one re-use lexically identical implementations without copying and pasting, or forcing everything to inherit from a single base class?
This is to reduce the maintenance effort required for a library of user controls that all inherit from things in System.Windows.Forms
and also override WndProc
in exactly the same way (the code is all copied and pasted, and I'm trying to eliminate or centralize it).
Note: I don't do a substantial amount of C# work, so forgive me if this question seems elementary or abuses the terminology in this realm.