Search code examples
c#xmlenumsenum-flags

Is there a way to convert from a list of strings to an enum flag in c#?


I have a list of strings in an xml document:

<properties>red yellow blue</properties>

and I have an enum:

[Flags]
public enum Properties 
{
    None    = 0,
    red = 1,
    yellow = 2,
    blue = 4,
    green = 8
}

Is there a way to convert the XML string into the enum flag value of 7 or 0111?

There are countless resources around about doing the reverse of this, but I'm having trouble finding any information on converting from a string to Flags.


Solution

  • Yes, but you need them to be comma separated:

    [Flags]
    public enum Test
    {
        A = 1,
        B = 2,
        C = 4
    }
    
    Test t;
    Enum.TryParse<Test>("A,B", out t);
    

    Since you can't have spaces in the names, you can just do a string replace of space to comma before calling TryParse.