Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an internal type used as protected field

Tags:

c#

.net

I have a class library with 2 public classes that inherit from an abstract class. On the abstract class I have a protected field that should only be accessible to the inherited classes. The type used for the field is that of an internal class.

For example I have:

internal class MyInternalClass
{
    ...
}

public abstract class MyAbstractClass
{
    protected MyInternalClass myField;
}

Now I understand that this won't work because if one of the classes deriving from MyAbstract class is extended outside of the assembly, access to myField would be illegal.

My question is how can I get things working while keeping MyInternalClass internal (it should not be accessible outside the assembly) and allowing classes within the assembly to extend MyAbstractClass with access to myField?

like image 310
zaq Avatar asked Sep 19 '12 20:09

zaq


1 Answers

Create a public interface that MyAbstractClass requires and MyInternalClass implements.

Something like this so you can have it be MyInternalClass by default but inject new behavior if you needed (for example, mocking):

internal class MyInternalClass : IMyInterface
{
}

public interface IMyInterface
{            
}

public abstract class MyAbstractClass
{
    protected IMyInterface myField;

    protected MyAbstractClass(IMyInterface required = null)
    {
        myField = required ?? new MyInternalClass();
    }
}
like image 61
Austin Salonen Avatar answered Oct 14 '22 09:10

Austin Salonen