-1

I want to define a method which returns true or false if a subset of an enum (first argument) contains an enum element (second element)

In other words, having an enum like:

public enum type { INST, INST_NAME, OPEN_BR, CLOSED_BR};

I wish to define a method like this one:

public bool check (IEnumerable <type> subset , type t)
       {if(subset.Contains t)
            return true;
        else
            return false;
       }

And then call it with:

check(new List<type>{INST, INST_NAME},type.INST);

Which returns true since the list contains INST. So the question is: do you know any more elegant way to implement this method (assuming that it works).

Thank you for your answers!

TwistAndShutter
  • 219
  • 2
  • 15

2 Answers2

2

Add [Flags] attribute to your enum. Set each option to be represented by an exclusive bit.

For example:

[Flags]
enum LogLevel
{
    App = 1 << 0,
    Exception = 1 << 1,
    Warning = 1 << 2,
    Measurement = 1 << 3,
    User = 1 << 4
}

Then implement your method like this:

bool IsSet(LogLevel levels, LogLevel levelInQuestion)
{
    return (levels & levelInQuestion) > 0;
}

Example Use:

LogLevel logLevels = LogLevel.App | LogLevel.Warning | LogLevel.Exception;
bool logWarnings = IsSet(logLevels, LogLevel.Warning);
Manthess
  • 121
  • 1
  • 3
0

You don't need a separate method to simplify this - you can just use the built-in Contains extension method:

var subset = new List<type>{INST, INST_NAME};

bool check = subset.Contains(type.INST);
D Stanley
  • 144,385
  • 11
  • 166
  • 231