Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get complex enum value string representation

Tags:

c#

enums

flags

Let's say I have this enum:

[Flags]
public enum SomeType
{    
    Val1 = 0,
    Val2 = 1,
    Val3 = 2,
    Val4 = 4,
    Val5 = 8,
    Val6 = 16,
    All = Val1 | Val2 | Val3 | Val4 | Val5 | Val6
}

and some variables:

SomeType easyType = SomeType.Val1 | SomeType.Val2;
SomeType complexType = SomeType.All;

If I want to loop through values of the first enum I can simply do:

foreach(string s in easyType.ToString().Split(','))
{ ... }

However, when I try to apply the same approach to the 'complexType' I get value 'All', which is of course valid because it's also one of possible values of the enum. But, is there a neat way to actually see of what values is the SomeType.All created of? I know I could make a manual loop through all the values like that:

if(complexType.HasFlag(ManualType.Val1) && ...
like image 303
IamDeveloper Avatar asked Feb 11 '11 11:02

IamDeveloper


1 Answers

var result = string.Join(",",
                 Enum.GetValues(typeof(SomeType))
                     .Cast<SomeType>()
                     .Where(v => complexType.HasFlag(v)));

You can write an extension method to avoid repeating yourself.

like image 160
Cheng Chen Avatar answered Jan 04 '23 06:01

Cheng Chen