Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a constructor that does not exist in base class

Tags:

c#

inheritance

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.

like image 946
MakePeaceGreatAgain Avatar asked Nov 10 '22 06:11

MakePeaceGreatAgain


1 Answers

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.

like image 58
Yuval Itzchakov Avatar answered Nov 14 '22 23:11

Yuval Itzchakov