Reputation: 1100
Iam writing a library. I have a class called Database and a class called DBManager... Database.cs is doing simple CRUD stuff for a single (defined in the contructor) database. DBManager is handling all the Database instances etc.
I want that users can only call DBManager and never instantiate a Database class for themselves (DBManager should be the only class doing this!) The layers are: User -> DBManager -> Database
How can i achieve something like this?
Upvotes: 0
Views: 107
Reputation: 3178
Mark it Internal:
public AccessibleClass
{
}
internal NonAccessibleClass
{
}
If you need the Database class to be usable from the outside but not instantiated, then simply change the constructor accessors.
public class Database
{
internal Database()
{
//initialize
}
}
However it sounds like you're going for the Factory pattern.
Upvotes: 4
Reputation: 27962
So currently both Database
and DBManager
are public
. And you want to limit instantiation of Database
to a controlled way:
I want that users can only call DBManager and never instantiate a Database class for themselves (DBManager should be the only class doing this!)
The easiest is adjusting accessibility of Database
's constructor using the internal
modifier:
public class Database
{
…
internal Database(string connectionString)
{
…
}
}
That way, only classes in the same assembly will be able to call the constructor.
Upvotes: 3