Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 462
user3163495 Avatar asked Dec 12 '25 08:12

user3163495


2 Answers

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 { ... }
}
like image 72
InBetween Avatar answered Dec 13 '25 20:12

InBetween


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";
}
like image 32
JuanR Avatar answered Dec 13 '25 21:12

JuanR