In C# is there a shorthand way to write this:
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneD
A nice little trick is to sort of reverse the way you usually use .Contains(), like:-
public static bool IsAllowed(int userID) {
return new int[] { Personnel.JaneDoe, Personnel.JohnDoe }.Contains(userID);
}
Where you can put as many entries in the array as you like.
If the Personnel.x is an enum you'd have some casting issues with this (and with the original code you posted), and in that case it'd be easier to use:-
public static bool IsAllowed(int userID) {
return Enum.IsDefined(typeof(Personnel), userID);
}
How about this?
public static class Extensions
{
public static bool In<T>(this T testValue, params T[] values)
{
return values.Contains(testValue);
}
}
Usage:
Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
// Do something
}
I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.