Reputation: 2671
I am looking for a visibility modifier for attributes of an inner class that would allow the outer class to modify/set a value but external classes could only get/read the value.
public class Outer {
public class Inner {
// I want this to be editable by Outer instances
// but read-only to other external classes.
public string attribute;
}
}
Upvotes: 2
Views: 1993
Reputation: 1959
Since Inner class member/atribute is not static, you cannot hold or modify the state of that member.
I think the example of John Angelo comes the closest you can get.
Upvotes: 0
Reputation: 57688
You don't have an access modifier for that, but you can get away with something like this:
public class Outer
{
private static Action<Inner, string> InnerAttributeSetter;
public class Inner
{
static Inner()
{
Outer.InnerAttributeSetter = (inner, att) => inner.Attribute = att;
}
public string Attribute { get; private set; }
}
public Outer()
{
var inner = new Inner();
InnerAttributeSetter(inner, "Value");
Console.WriteLine(inner.Attribute);
}
}
Basically you taking advantage of the fact that nested classes have access to private
members of the enclosing class and providing for the enclosing class a proxy to set the attribute
property for a given Inner
instance. Since external classes do not have access to this proxy you satisfied your requirement.
Upvotes: 4