Convert some bool properties to a flags enum
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;
}
}
}
Instead of using branching in your code you can do bitwise arithmetic combined with a small function to simplify the code:
T GetFlag<T>(Boolean value, T flag) {
return value ? flag : default(T);
}
To compute the enum value you can use this expression:
var flagEnum = GetFlag(legacyClass.PropA, FlagEnum.EnumValue1)
| GetFlag(legacyClass.PropB, FlagEnum.EnumValue2)
| GetFlag(legacyClass.PropC, FlagEnum.EnumValue3);
Note that your code will throw an ArgumentException
if none of the flags are set. This code will instead compute default(FlagEnum)
which in this case is 0.
How about this?
public DtoClass(LegacyClass legacyClass)
{
if (!legacyClass.PropA && !legacyClass.PropB && !legacyClass.PropC)
{
throw new ArgumentException();
}
FlagEnum = ((legacyClass.PropA) ? FlagEnum.EnumValue1 : FlagEnum)
| ((legacyClass.PropB) ? FlagEnum.EnumValue2 : FlagEnum)
| ((legacyClass.PropC) ? FlagEnum.EnumValue3 : FlagEnum);
}