Search code examples
c#classstaticprivatepublic

C# - Make a private nested class visible through a public property


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

Solution

  • 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 { ... }
    }