Given the following inheritance tree, what would be the best way of implementing it in a way that works?
abstract class Foo<T> : IEnumerable<T>
{
public abstract Bar CreateBar();
}
class Bar<T> : Foo<T>
{
// Bar's provide a proxy interface to Foo's and limit access nicely.
// The general public shouldn't be making these though, they have access
// via CreateBar()
protected Bar(Foo base)
{
// snip...
}
}
class Baz<T> : Foo<T>
{
public Bar CreateBar()
{
return new Bar(this);
}
}
This fails with: 'Bar.Bar()' is inaccessible due to its protection level
.
I don't want the constructor being public, only classes that inherit from Foo
should be able to create Bar
s. Bar
is a specialised Foo
, and any type of Foo
should be able to create one. Public internal is an 'option' here, as the majority of the predefined extensions to Foo
will be internal to the DLL, but I consider this a sloppy answer, since anyone who comes along later who wants to create their own type of Foo
or Baz
(which is likely to happen) will be stuck with a default CreateBar()
implementation, which may or may not meet their needs.
Perhaps there is a way of refactoring this to make it work nicely? I'm banging my head on the wall trying to design this so it'll work though.
Edit (More info):
Slightly more concrete: Foo is implementing IEnumerable and long story short, Bar is providing the same interface, but to a limited subset of that enumerable object. All Foo's should be able to create subsets of themselves (ie. Bar) and return it. But I don't want to have everyone who ever wants to implement a Foo to have to worry about this, because Bar will do the proxying and worry about limiting the range, etc.