I’ve got a class that I would like to inherit. i.e. ExpenseForm should inherit from Spreadsheet. Spreadsheet is provided by a third party: I can’t change it.
But parent class instances are usually generated with a static method:
Spreadsheet myExpenses = Spreadsheet.Open(filename);
(And Spreadsheet implements iDisposable, so the above statement is actually at the top of a using section, but I don’t think that really affects this.)
I’d like to have
ExpenseForm myExpenses = ExpenseForm.Open(filename);
This fails, of course, since ExpenseForm.Open (inherited from Spreadsheet) returns a Spreadsheet object.
What’s the best way to solve this? Maybe extension methods? (I have no experience with those.)
I’ve gone a different direction; ExpenseForm now has an instance of Spreadsheet. (This feels a little messier, since I have to keep track of my disposable object to clean up when I’m done.) But it seems like I’m missing a way to solve the original inheritance problem.
Well you can create your own
ExpenseForm.Openmethod easily enough:That’s assuming you can create a subclass, i.e. that there are appropriate constructors you can chain to. You say that you would normally use
Spreadsheet.Open, but are there protected or public constructors available?Personally I’d favour the composition route anyway – do you actually want other code to treat an
ExpenseFormas if it were any other kind ofSpreadsheet? I’m generally more of a fan of composition than inheritance – it makes code easier to reason about, in my experience.