Reputation: 845
As a part of learning process, I am writing simple IM app, using Remoting in .NET. As of now it is simple console app and it works as i expect. Thinking about next features/functionalities, I've stuck in a situation represented by the code below:
public static class UserManager {
public static started { get; private set; }
private static List<User> users;
static UserManager() {
users = List<User>();
started = true;
}
public static addUser(int _userID) {}
public static activateUser(int _userID) {
foreach (User u in users) {
if (u.userID == _userID) {
u.setActive();
break;
}
}
}
}
class User {
public int userID { get; private set; }
public bool active { get; private set; }
public User(int _userID) {
userID = _userID;
}
public void setActive() {
// only UserManager should be allowed to modify user state
}
}
I want to make only UserManager static class be allowed to modify states of it's users list. I was thinking about "friend" clause but as I understand, there is no such construct in C#. Would it be enough just checking (inside User class methods), if calling "object" is of class UserManager?
I would appreciate any input/advice, including those saying "don't do that as You try to do, better make it using.."
PS. Didn't know which Title should i choose, feel free (more experienced programmers/so users) to change it if ther is more accurate.
Upvotes: 0
Views: 366
Reputation: 1499890
The only options I can think of for really restricting access to the members of User
to UserManager
at compile time are:
UserManager
a nested class within User
and make the members privateIf you just make the members internal, it will limit access to the assembly anyway - can you not make the assembly sufficiently small that you can trust code written within that assembly?
(Just as a friendly bit of advice, I suggest you look up the Microsoft .NET naming conventions - it'll make your code look much more like idiomatic C#.)
Upvotes: 0
Reputation: 172616
You can put the UserManager
and User
classes in their own assembly and mark parts of the API as internal
(which is the equivalent of VB's Friend
). This enables you to restrict access from outside that assembly.
Another way to restrict access is by doing role based security. .NET has the PrincipalPermissionAttribute for this:
public static class UserManager
{
[PrincipalPermission(SecurityAction.Demand,
Role = "Administrators")]
public static void AddUser(int userId) { }
}
Note that this will only work when you know the role of the user, but it is especially useful in scenario's such as web sites (ASP.NET WebForms / MVC) and web services (WCF) were users normally log on.
Upvotes: 1