In C#, it’s not straightforward to limit access to an inner class from outside its outer class. For instance, if you want to expose an inner class as a property and only allow read access to one of its properties while preventing write access. There are several ways to solve this problem. One method involves using interfaces, which in my opinion, offers a clean solution.
The example below shows how a integer value called MyValue inside MyInnerClass can read publicly but only be set by its outer-class ‘MyOuterClass’.
The code should be self-explanatory.
public class MyOuterClass
{
//Define the setters to be used in "OuterClass"
public interface IInnerClass
{
//The get will be provided by MyInnerClass,
//no need to implement it in the interface
int MyValue { set; }
}
public MyInnerClass InnerClass = new MyInnerClass();
private readonly IInnerClass myInnerClass;
public MyOuterClass()
{
myInnerClass = InnerClass;
}
//A method to test access
void test()
{
myInnerClass.MyValue = 123;
}
public class MyInnerClass : IInnerClass
{
//Used outside OuterClass when OuterClass.InnerClass
//properties are called
public int MyValue { get; private set; }
// Implement the interface which can have other
// access specifiers! get is not part of the
// interface and is provided by MyInnerClass
// This setter can only be called in MyOuterClass
int IInnerClass.MyValue { set => this.MyValue = value; }
}
}
In other parts of the code the code fragment below will yield the error “Error CS0272 The property or indexer ‘MyOuterClass.MyInnerClass.MyValue’ cannot be used in this context because the set accessor is inaccessible”
MyOuterClass c = new MyOuterClass();
c.InnerClass.MyValue = 123;