Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# public class that can only be instantiated by its parent

Tags:

c#

oop

Is it possible to have a nested class that is public but can only be instantiated by it's parent class e.g.

 public class parent
{
    public class child
    {
        public string someValue;
    }

    public child getChild()
    {
        return new child();
    }
}

in this example the 'child' class could be instantiated by code external to 'parent' . I want the external code to be able to view the 'child' type but not be able to construct it's own one.

e.g

var someChild = new parent.child();
like image 893
MakkyNZ Avatar asked Nov 29 '22 14:11

MakkyNZ


1 Answers

  1. Make a public interface.
  2. Make the child class private.
  3. Make the child implement the interface.
  4. Have the getChild method make a new child and return the interface type.

As mentioned in the comments and other answers, you can also change the access modifier on the constructor(s) of the inner class to either internal or private while leaving the inner class itself public.

like image 119
Servy Avatar answered Dec 15 '22 06:12

Servy