user3412984
user3412984

Reputation: 75

Preventing instantiation of an internal class used in its outer class from a third, external class

With the following structure:

public class OuterClass {
   public InnerClass foo {get; private set}
   public OuterClass() {
      foo = new InnerClass()
   }
   public class InnerClass {
      sometype somevar;
      public InnerClass()
   }
}

How is access to the inner class constructor restricted from a third class as so:

OuterClass outerclassinstance = new OuterClass();
outerclassinstance.foo.somevar; // allowed
OuterClass.Innerclass innerclassinstance = new Outerclass.InnerClass(); // not allowed
innerclassinstance.somevar // not allowed

If I make InnerClass private I get an Inconsistent accessibility error for 'foo', and if I make foo private as well it naturally can't be accessed from a third class.

Is it even possible or should I be looking for an entirely different solution entirely? Is there a structural design pattern that resolves this issue?

Upvotes: 3

Views: 51

Answers (2)

ksdev
ksdev

Reputation: 56

This may be Helpful :

public class OuterClass {
   public InnerClass foo {get; private set}
   public OuterClass() {
      foo = new InnerClass()
   }
   public class InnerClass {
      protected sometype somevar;
      protected InnerClass()
   }
}

Upvotes: 0

PepitoSh
PepitoSh

Reputation: 1836

Try this:

public interface IInnerClass {
}

public class OuterClass {
   public IInnerClass foo {get; private set;}
   public OuterClass() {
      foo = new InnerClass();
   }
   private class InnerClass : IInnerClass {
      sometype somevar;
      public InnerClass(){}
   }
}

Your InnerClass is private, but you can have a public interface to it.

Upvotes: 4

Related Questions