I have the following code that does not compile:
public class Outer
{
public Inner MyField = new Inner(); //error here: "field type is less accessible than field"
private class Inner
{
public string Message = "Hello";
}
}
I must be able to use the class like so:
var MyObject = new Outer();
Console.WriteLine(MyObject.MyField.Message); //should output "Hello"
"Inner" must ONLY be instantiable from within "Outer", so this should NOT be allowed:
var MyObject = new Outer.Inner(); //I do not want users to be able to instantiate "Inner" directly
The typical way to solve this is via an interface:
public class Outer
{
public IInner Inner = new Inner();
public interface IInner { ... }
private class Inner: IInner { ... }
}
IInner need not be nested, any choice is viable.
An interesting variation of this pattern is when the nested classes inherit from the outer class. This is a pretty handy code structure that allows really elegant solutions:
public abstract class Outer
{
public static Outer GetOuter(...)
{
if (someConditionMet) return new InnerSpecialized1();
return new InnerSpecialized2();
}
private Outer() { ... } //avoids anyone extending Outer
private class InnerSpecialized1: Outer { ... }
private class InnerSpecialized2: Outer { ... }
}
You need to expose the field's getter only and construct the instance within the class:
public class Outer
{
public Outer()
{
MyField = new MyField();
}
public Inner MyField {get; private set;}
}
public class Inner
{
internal Inner()
{
}
public string Message = "Hello";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With