C # Limit class instance creation in namespace

I have two objects: RoomManager and Room , there will be several Room and one RoomManager . I want RoomManager be the only one who managed to create the Room object. So I'm wondering if there is a way to make the Room constructor (and other Room methods / properties) available only to RoomManager . I thought maybe moving them to my namespace and making Room private or internal or something else. From Accessibility Levels (link to C #) I can see that the inside is for the whole assembly, but not just for the namespace.

+8
access-modifiers c # class-design
source share
4 answers

No, C # (and .NET in general) does not have namespace specific access modifiers.

One of the rather hacky solutions would be to have Room only have a private constructor and make RoomManager a nested class (possibly just called by the manager):

 public class Room { private Room() {} public class Manager { public Room CreateRoom() { return new Room(); // And do other stuff, presumably } } } 

Use it as follows:

 Room.Manager manager = new Room.Manager(); Room room = manager.CreateRoom(); 

As I said, this is a bit of hacks. Of course, you could put Room and RoomManager in your own assembly.

+9
source share

You can do something like this:

 var room = Room.Factory.Create(); 

If the room constructor is closed, it will still be accessible from Room.Factory if you declare a factory class inside the room class.

+3
source share

Defining a room inside RoomManager itself and creating its own private constructor can be useful.

EDIT: But the best solution, I think, is to extract the abstract class of the room and provide that class to the clients.

No one can instantiate an abstract class.

+1
source share

You must implement the ' Singleton pattern '. It creates an object only once, and any subsequent attempts to create an object of this type will actually return the already created object.
You must create a factory class that will implement a singleton for RoomManager . Room , in turn, must be a private RoomNamager type. RoomNamager must have a method for creating a Room . But in this case, you cannot access Room properties outside the RoomManager class. To solve this problem, I recommend that you create an open IRoom interface that will provide access to the functionality of the room. Thus, your create room method returns an IRoom interface.

0
source share

All Articles