Convert some bool properties to a flags enum

giammin picture giammin · Oct 29, 2013 · Viewed 7.8k times · Source

I need to convert a legacy class with 3 bool properties to a flag enum.

I know that at least one of those properties is true.

[Flags]
public enum FlagEnum
{
    EnumValue1 = 1,
    EnumValue2 = 2,
    EnumValue3 = 4
}

public class LegacyClass
{
    public bool PropA { get; set; }
    public bool PropB { get; set; }
    public bool PropC { get; set; }
}

public class DtoClass
{
    public FlagEnum FlagEnum { get; set; }

    public DtoClass(LegacyClass legacyClass)
    {
        if (!legacyClass.PropA && !legacyClass.PropB && !legacyClass.PropC)
        {
            throw new ArgumentException();
        }

        if (legacyClass.PropA)
        {
            FlagEnum = FlagEnum.EnumValue1;
        }
        if (legacyClass.PropB)
        {
            if (legacyClass.PropA)
            {
                FlagEnum = FlagEnum.EnumValue1|FlagEnum.EnumValue2;
            }
            else
            {
                FlagEnum = FlagEnum.EnumValue2;
            }
        }
        if (legacyClass.PropC)
        {
            if (legacyClass.PropA||legacyClass.PropB)
            {
                FlagEnum = FlagEnum | FlagEnum.EnumValue3;
            }
            else
            {
                FlagEnum = FlagEnum.EnumValue3;
            }
        }
    }
}

Is there a more elegant or concise way to do this considering that I may run into a case with even more properties and flags to set?

Answer

Fredou picture Fredou · Oct 29, 2013

how about something like this?

using System;

namespace ConsoleApplication1
{

    [Flags]
    public enum FlagEnum
    {
        EnumValue1 = 1,
        EnumValue2 = 2,
        EnumValue3 = 4
    }

    public static class LegacyClass
    {
        public static bool PropA { get; set; }
        public static bool PropB { get; set; }
        public static bool PropC { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            LegacyClass.PropB = true;
            FlagEnum result = LegacyClass.PropA ? FlagEnum.EnumValue1 : 0;
            result |= LegacyClass.PropB ? FlagEnum.EnumValue2 : 0;
            result |= LegacyClass.PropC ? FlagEnum.EnumValue3 : 0;
        }
    }
}