In C# is there a shorthand way to write this:
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneD
I would encapsulate the list of allowed IDs as data not code. Then it's source can be changed easily later on.
List<int> allowedIDs = ...;
public bool IsAllowed(int userID)
{
return allowedIDs.Contains(userID);
}
If using .NET 3.5, you can use IEnumerable
instead of List
thanks to extension methods.
(This function shouldn't be static. See this posting: using too much static bad or good ?.)
Here's the closest that I can think of:
using System.Linq;
public static bool IsAllowed(int userID)
{
return new Personnel[]
{ Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID);
}
Just another syntax idea:
return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID);
Are permissions user-id based? If so, you may end up with a better solution by going to role based permissions. Or you may end up having to edit that method quite frequently to add additional users to the "allowed users" list.
For example, enum UserRole { User, Administrator, LordEmperor }
class User {
public UserRole Role{get; set;}
public string Name {get; set;}
public int UserId {get; set;}
}
public static bool IsAllowed(User user) {
return user.Role == UserRole.LordEmperor;
}
Can you write an iterator for Personnel.
public static bool IsAllowed(int userID)
{
return (Personnel.Contains(userID))
}
public bool Contains(int userID) : extends Personnel (i think that is how it is written)
{
foreach (int id in Personnel)
if (id == userid)
return true;
return false;
}
How about something like this:
public static bool IsAllowed(int userID) {
List<int> IDs = new List<string> { 1,2,3,4,5 };
return IDs.Contains(userID);
}
(You could of course change the static status, initialize the IDs class in some other place, use an IEnumerable<>, etc, based on your needs. The main point is that the closest equivalent to the in operator in SQL is the Collection.Contains() function.)