5

I have a class that expects an IWorkspace to be created:

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

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

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

The above won´t compile with following error:

Cannot access protected member MyClass.workspace' via a qualifier of type 'MyClass'; the qualifier must be of type 'Derived' (or derived from it)

So what I´m trying to achieve is copying the base-class´ members to the derived one and create into a new instance of the latter. The reason why I do not use a constructor for IWorkspace within my derived class is that I do not have any access to such a workspace within the client-code, only to the instance of MyClass to be copied.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111

1 Answers1

1

Since you don't have access to MyClass source and IWorkspace isn't available, the best thing you can do is encapsulate MyClass instead of derive it, and have someone externally provide the dependencies:

public class MyClassWrapper
{
    private readonly MyClass myClass;
    public MyClassWrapper(MyClass myClass)
    {
        this.myClass = myClass;
    }

    // Wrap any methods you depend on here
}

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

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321