Regarding your "First" proposal with interfaces: you can also implement the interface explicitly: "A class that implements an interface can explicitly implement a member of that interface. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface. " See / Source: http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx
However, i would choose the Composition approach. "Favor Composition over Inheritance", also see Prefer composition over inheritance?
Ideally, i would constructor-inject B
into A
by dependency injection, that should help mitigate your b == null
concern.
Note:
Using a static method / extension method (is a static method, too...) makes unit-testing A
(respectively faking B
) very hard, which is why i would forgo these solutions completely.
Edit:
If you don't need B.doMethodB
accessible from anyone else than A
, you can also make B
an abstract
class and B.doMethodB
a protected
method.
But i was thinking that you already know that ;-)
(And because of the testing issues i would still favor composition over inheritance).