Create a constructor that does not exist in the base class

I have a class that is awaiting the creation of IWorkspace :

 public class MyClass { protected IWorkspace workspace; public MyClass(IWorkspace w) { this.workspace = w; } } 

and Derived derived class. In this derived class, I have copy-constrcutor that should create a Derived instance based on the MyClass instance.

 public class Derived : MyClass{ public Derived(MyClass m) : base(m.workspace) { } } 

The above will not compile with the following error:

Unable to access protected member MyClass.workspace 'through qualifier of type MyClass; qualifier must be of type Derived (or derived from it)

So what I'm trying to achieve is copying the members of the base class into a derived one and creating the latter in a new instance. The reason I don't use the constructor for IWorkspace in my derived class is because I do not have access to such a workspace inside the client code, only for the MyClass instance to copy.

+5
source share
1 answer

Since you do not have access to the MyClass source, and IWorkspace not available, it is best to encapsulate MyClass instead of IWorkspace it, and force someone to provide dependencies from the outside:

 public class MyClassWrapper { private readonly MyClass myClass; public MyClassWrapper(MyClass myClass) { this.myClass = myClass; } // Wrap any methods you depend on here } 

If the click comes and you have no alternative, you can use reflection to get a Workspace instance from MyClass , but that would be an ugly hack.

+1
source

All Articles