Inherit a class, but is it usually created using a static method?

I have a class that I would like to inherit. that is, ExpenseForm must inherit from the table. The spreadsheet is provided by a third party: I cannot change it.

But instances of the parent class are usually generated by the static method:

Spreadsheet myExpenses = Spreadsheet.Open(filename); 

(And Spreadsheet implements iDisposable, so the above statement is actually at the top of the section, but I don't think it really affects that.)

I would like to have

 ExpenseForm myExpenses = ExpenseForm.Open(filename); 

This fails, of course, since ExpenseForm.Open (inherited from Spreadsheet) returns a Spreadsheet object.

What is the best way to solve this problem? Maybe extension methods? (I have no experience with them.)

I went in a different direction; ExpenseForm now has an instance of the table. (This feels a little messier, as I have to keep track of my disposable object in order to clear it when done.) But it seems like I am missing a way to solve the original inheritance problem.

+4
source share
2 answers

Well, you can easily create your own ExpenseForm.Open method:

 public static new ExpenseForm Open(string file) { // Do whatever you need } 

Assuming you can create a subclass, i.e. There are corresponding constructors to which you can bind. You say you usually use Spreadsheet.Open , but are there protected or public constructors?

In any case, I would approve of the compositional route - do you really want other code to handle ExpenseForm , as if it were a different type of Spreadsheet ? I'm generally more of a fan of composition than inheritance - it makes code easier to reason from, in my experience.

+1
source

If Spreadsheet objects can only be created using a static function, then inheritance is not an option. Just specify your old Open function in ExpenseForm , which returns an object of this type.

+1
source

All Articles