Receive an instance of A
in the constructor. Even better is to have A
inherit some interface and receive that interface in the constructor.
public interface IA {}
public class A : IA {}
public class B
{
public IA AInstance { get; set; }
public B (IA a)
{
AInstance = a;
}
public void test()
{
/* do something with `AInstance` */
}
}
Look into the concepts of Dependency Injection and Inversion of Control:
- What is dependency injection?
- What is Inversion of Control?
And wrap it all under the SOLID principals
If you can't get IA
as a dependency but need to create a new instance of it in your B
class then use the Factory design pattern and let B
depend on some instance of ISomeFactory