Marcus
Marcus

Reputation: 8659

Have x number of classes only accessible to each other?

Given the available accessibility Levels, is there any pattern or proper approach to make class A accessible only from class B and C and vice versa, where there is no inheritance relation between class A, class B and class C? (Preferrably at compile time)

A,B and C are siblings and are located in the same namespace.

So far, the only thing that comes to mind is:

The latter seems to be the best approach, but is there any other way? I am looking for something like InternalsVisibleTo but inside an assembly.

Upvotes: 0

Views: 61

Answers (2)

D Stanley
D Stanley

Reputation: 152511

Well you could create a containing class that has the three classes as private nested classes:

public class O
{
    private class A { private void Test() {B b = new B(); C c = new C(); }}
    private class B { private void Test() {A a = new A(); C c = new C(); }}
    private class C { private void Test() {B b = new B(); A a = new A(); }}
}

public class Hacker
{
    O.A a = new O.A();  // fail
}

Note that nesting classes does not imply any sort of inheritance relationship - it's used purely for accessibility purposes.

But what's the point of the three classes if they can't be accessed outside of their little circle? What does use those classes?

Upvotes: 2

weston
weston

Reputation: 54781

The strictest you can get (whilst still being able to see it from other classes) is internal but then as you know, any class in that assembly can see that class.

It would be nice to have something like package private in Java, which is private except to other members of that package (namespace) but alas C# doesn't have that.

However you could arrange your assemblies to enforce this:

Instead of:

Assembly
   -internal A
   -B (uses A)
   -C (uses A)
   -D (uses the public classes of Assembly1, but can also see A)

Separate them to:

Assembly1
   -internal A
   -B (uses A)
   -C (uses A)
Assembly2
   -references Assembly1
   -D (uses the public classes of Assembly1, can't see A)

You can't have a circular reference, so unlike them all sharing an assembly, this enforces the direction of the dependencies from Assembly2 to Assembly1 only.

Related: I'd like a warning about circular namespace dependency

Upvotes: 1

Related Questions