Preventing instantiation of an internal class used in its outer class from a third, external class
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?
2 Answers
2
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.
You can put in the interface declaration anything you wish to expose to outside. Of course you have to implement the interface in InnerClass accordingly.
– PepitoSh
Jul 3 at 10:29
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()
}
}
The protected keyword plays a role in inheritance. There is no such thing here.
– PepitoSh
Jul 3 at 10:01
protected keyword is access spacifier and its use in Inheritance.
– kamlesht
Jul 3 at 10:02
You cannot even use a protected InnerClass constructor with your example.
– PepitoSh
Jul 3 at 10:05
why ? protected allows access to only its child class instance.
– kamlesht
Jul 3 at 10:07
Did you put the code in VS, or just speculate here? I did.
– PepitoSh
Jul 3 at 10:26
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This has the desired functionality other than 'somevar' not being accessible through the third, external class. new OuterClass().foo.somevar // IInnerClass does not contain a definition for 'somevar'. This is, unless somevar is included within the interface. Must it be included in the interface, then?
– user3412984
Jul 3 at 10:20