Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Limit creation of class instance to within namespace

I have two objects, RoomManager and Room, there will be several Rooms and one RoomManager. I want the RoomManager to be the only one allowed to create a Room object. So I'm wondering if there is a way to make the Room constructor (and the rest of the Room methods/properties) only accessible to the RoomManager. I was thinking maybe moving them to their own namespace and making Room private or internal or something. From Accessibility Levels (C# Reference) I see that internal is for the entire assembly though, not just the namespace.

like image 782
jb. Avatar asked Apr 13 '11 07:04

jb.


3 Answers

No, C# (and .NET in general) has no access modifiers which are specific to namespaces.

One fairly hack solution would be to make Room just have a private constructor, and make RoomManager a nested class (possibly just called Manager):

public class Room
{
    private Room() {}

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

Use it like this:

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

As I say, that's a bit hacky though. You could put Room and RoomManager in their own assembly, of course.

like image 69
Jon Skeet Avatar answered Oct 28 '22 08:10

Jon Skeet


You can do something like this:

var room = Room.Factory.Create();

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

like image 27
Ilya Kogan Avatar answered Oct 28 '22 09:10

Ilya Kogan


Defining the Room inside of RoomManager itself and making it's constructor private could be helpful.

EDIT : But the best solution I think is that to extract an abstract class of the Room, and expose that class to clients.

No one can create an instance of the abstract class.

like image 28
Jahan Zinedine Avatar answered Oct 28 '22 08:10

Jahan Zinedine