Given the example below, is it possible to extend class Foo with ClassyFoo and have Bar instances created by ClassyFoo inherrit from ClassyFoo while maintaining that Bar instances created by Foo still inherit from Foo?
For example:
class Foo
{
protected Foo()
{
Console.WriteLine("Setting up Foo");
}
public static void Show()
{
Console.WriteLine("Showing Foo");
var bar = new Bar();
}
}
class ClassyFoo : Foo
{
public ClassyFoo() : base()
{
Console.WriteLine("Setting up Classy Foo");
}
public new static void Show()
{
Console.WriteLine("Showing Classy Foo");
var bar = new Bar();
}
}
class Bar: Foo
{
public Bar() : base()
{
Console.WriteLine("Setting up Bar");
}
}
The desired output of ClassyFoo.Show() being:
Showing Classy Foo
Setting up Foo
Setting up Classy Foo
Setting up Bar
And the output of Foo.Show() being:
Showing Foo
Setting up Foo
Setting up Bar
The situation is class Bar adds some configuration/specialization to Foo, but so does Classy Foo. But both Bar and ClassyFoo’s specialization can exist on the same object.
I’m trying to avoid having a duplicate Bar that inherits from ClassyFoo. In reality there are multiple Bars but just one ClassyFoo, so that would be a lot of duplication.
I’d say that is not possible. One class has exactly one base class.
You might be able to implement ClassyFoo and/or Bar as Interfaces and let the actual classes inherit from one, or the other, or both.
Depending on the actual representations and code reuse I’d make both interfaces (similar handling) or one an abstract class (you can stuff a bunch of code in there)