"in" expression for comparing multiple values #8028
-
MotivationA common need I've had for some time is to check whether a value is part of a set, directly comparing whether the object is equal to something belonging to the set. Since the .NET Framework, I have been using something similar to: int value = 20;
if (new int[] { 10, 20, 30 }.Contains(value)) {
// the specified set contains the value
} In a recent project, I've extended an public static bool In<T>(this T value, params T[] values)
{
foreach (T source in values)
{
if (source.Equals(value))
{
return true;
}
}
return false;
} And the usage: Level level = Level.Administrator;
if (level.In(Level.Administrator, Level.Manager))
{
Console.WriteLine("User is administrator or manager!");
}
else
{
Console.WriteLine("Access danied");
} SyntaxBut, I wonder if a syntax-sugar could reduce the direct code in compilation, where the suggested use of the if (level in [Level.Administrator, Level.Manager]) {
// do something
}
if (level not in [Level.Administrator, Level.Manager]) {
// negation of above condition
} Would be the reduced equivalent to: if ((level.Equals(Level.Administrator) || level.Equals(Level.Manager))) {
// do something
}
if ( (!level.Equals(Level.Administrator) && !level.Equals(Level.Manager)) ) {
// negation
} Concerns
AlternativesI don't see any other than defining the method |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
You can use disjunctive patterns ( if (value is 10 or 20 or 30) { }
if (level is Level.Administrator or Level.Manager) { } |
Beta Was this translation helpful? Give feedback.
-
In your example, you said that you don't allocate an array but you are allocating an array for |
Beta Was this translation helpful? Give feedback.
You can use disjunctive patterns (
or
):