Given the enum
:
[Flags]
public enum mytest
{
a = 1,
b = 2,
c = 4
}
I\'ve come up with two ways to represent all va
Use Enumerable.Aggregate() to bitwise-or them together. This will work even if you have enum values that represent multiple set bits, as opposed to Sum()
.
var myTestValues = (MyTest[]) typeof(MyTest).GetEnumValues();
var sum = myTestValues.Aggregate((a, b) => a | b);
sum.Dump();
It's a little tricky to make this generic because you can't constrain generic types to be enums, nor do the primitive types have any subtype relationship to one another. The best I could come up with assumes that the underlying type is int
which should be good enough most of the time:
TEnum AllEnums()
{
var values = typeof(TEnum).GetEnumValues().Cast();
return (TEnum) (object) values.Aggregate((a,b) => a|b);
}