C # public class that can only be created by its parent

Is it possible that the nested class is public, but can only be created by its parent class, for example

public class parent { public class child { public string someValue; } public child getChild() { return new child(); } } 

in this example, the "child" class can be instantiated with code external to the "parent". I want external code to be able to view the "child" type, but not be able to create its own.

eg

 var someChild = new parent.child(); 
+4
source share
3 answers
  • Make a public interface.
  • Make the child class private.
  • Make the child an implemented interface.
  • Ask the getChild method to create a new child and return an 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 inner or private, leaving the inner class itself open.

+13
source

Define an internal empty constructor

 public class child { internal child() {} public string someValue; } 
+3
source

You can limit the creation to your assembly by setting the protection level of your constructor (child class) to internal .

Or an interface, as @Servy said.

+2
source

Source: https://habr.com/ru/post/1412794/


All Articles