Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if enum has all flags

Tags:

c#

.net

enums

I'm trying to know if a enum value has defined all flags. The enum is defined as following:

[Flags]
public enum ProgrammingSkills
{
    None = 0,
    CSharp = 1,
    VBNet = 2,
    Java = 4,
    C = 8,
}

I cannot change the enum to define 'All', because that enum is defined in a dll library.

Of course I can iterate over all enum values, but is there any better/shorter/smarter way to determine if a enum value has defined ALL values?


EDIT:

I would like to have working code even the enum changes.

like image 606
Daniel Peñalba Avatar asked Jan 24 '26 03:01

Daniel Peñalba


2 Answers

I don't know if it's better but it is definitely shorter and will work if you modify the enum in the future:

bool result = Enum.GetValues(typeof(ProgrammingSkills))
      .Cast<ProgrammingSkills>()
      .All(enumValue.HasFlag);
like image 190
Selman Genç Avatar answered Jan 25 '26 18:01

Selman Genç


You could do the following:

var hasAll = val == (ProgrammingSkills.CSharp | ProgrammingSkills.VBNet
    | ProgrammingSkills.Java | ProgrammingSkills.C);

Or shorter, but not really good for maintenance:

var hasAll = (int)val == 15; // 15 = 1 + 2 + 4 + 8

Or in a generic way:

var hasAll = (int)val == Enum.GetValues(typeof(ProgrammingSkills))
                             .OfType<ProgrammingSkills>().Sum(v => (int)v);
like image 34
Christoph Fink Avatar answered Jan 25 '26 18:01

Christoph Fink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!