Taco
Taco

Reputation: 2923

Prevent Exposure of Base Classes (Abstract Classes)

So I looked through many related questions and none of them seem to fit all the way. At least not in my current understanding. As this is a simple issue, I'm going to be concise with my question and code.

I have five classes:

internal class A
internal abstract class B : A
internal abstract class C : B
public class D : C
public class E {
    public void X(C c) { }
}

There is an obvious accessibility issue here with the parameter C being used in a public method. I need to access class D without exposing class C. I believe this may be due to the nature of the abstract keyword, and my minimal experience with using it.

To date I have never had a known need to create an abstract class, and this is my first time dealing with it on this level. From my understanding, it isn't really necessary in this case to use abstract classes so long as I remember to implement everything properly.


My Questions


Notes

I've looked at many related posts (here are a few of them):

Upvotes: 0

Views: 218

Answers (1)

JuanR
JuanR

Reputation: 7803

You can use interfaces to hide the details. Consider this:

//This represents the contract, regardless of the underlying object
public interface ISomeObject
{

}

//Class is internal, but implements the interface
internal class A : ISomeObject { }
internal abstract class B : A { }
internal abstract class C : B { }

//Class D is still internal
internal class D : C { }

public class E
{   
    //Method uses interface, which is public     
    public void X(ISomeObject c) { }

    public ISomeObject DoSomething()
    {
        //Create internal class, return it for use (as a contract)
        return new D();
    }
}

Sample usage:

var e = new E();
var result = e.DoSomething();
e.X(result);

This works because from an external point of view, you are dealing with a public contract, not the actual implementation.

Upvotes: 2

Related Questions