Also see updates at the end of the question ...
Given the following situation:
[Flags] enum SourceEnum { SNone = 0x00, SA = 0x01, SB = 0x02, SC = 0x04, SD = 0x08, SAB = SA | SB, SALL = -1, } [Flags] enum DestEnum { DNone = 0x00, DA = 0x01, DB = 0x02, DC = 0x04, DALL = 0xFF, }
I would like to convert one type of enumeration into another and vice versa based on a matching function using names similar to the large switch (), but since this is an enumeration of flags, it is difficult for me to create such a procedure to be universal.
Basically, I want something like the following:
Example # 1
SourceEnum source = SourceEnum.SA; DestEnum dest = Map<Source, Dest> (source); Assert.That (dest, Is.EqualTo (DestEnum.DA));
Example # 2
SourceEnum source = SourceEnum.SA | SourceEnum.SB; DestEnum dest = Map<Source, Dest> (source); Assert.That (dest, Is.EqualTo (DestEnum.DA | DestEnum.DB));
Example # 3
SourceEnum source = SourceEnum.SAB; DestEnum dest = Map<Source, Dest> (source); Assert.That (dest, Is.EqualTo (DestEnum.DA | DestEnum.DB));
Example # 4
SourceEnum source = SourceEnum.SALL; DestEnum dest = Map<Source, Dest> (source); Assert.That (dest, Is.EqualTo (DestEnum.DALL));
Example # 5
SourceEnum source = SourceEnum.SD; var ex = Assert.Throws<Exception> (() => Map<Source, Dest> (source)); Assert.That (ex.Message, Is.EqualTo ("Cannot map SourceEnum.SD to DestEnum!"));
The Map () function can accept a delegate to provide the actual mapping, but I still need to have several functions to help with such a bit deletion ...
DestEnum SourceToDestMapper (SourceEnum source) { // Switch cannot work with bit fields enumeration... // This is to give the general idea... switch (source) { case SourceEnum.SNone: return DestEnum.DNone; case SourceEnum.SA: return DestEnum.DA; case SourceEnum.SAB: return DestEnum.DA | DestEnum.DB; ... default: throw new Exception ("Cannot map " + source.ToString() + " to DestEnum!"); } }
EDIT: CONFIRM
The values โโof the definitions of the enumerations may correspond to each other, but this is not necessary.
For example, it could be:
enum SourceEnum { SA = 0x08, SB = 0x20, SC = 0x10, SAB = SA | SB, SABC = SA | SB | SC, } enum DestEnum { DA = 0x04, DB = 0x80, DC = 0x01, DAB = DA | DB, }
EDIT: additional information
I am considering a way to perform custom enum flag matching, rather than based on name patterns. However, the names are used in a custom mapping function.
I could very well have a SourceToDestMapper function trying to map SA to DC, for example ...
The main problem is that the SourceToDestMapper function is supplied with each source flag and observance of the flag values โโhaving several sets of bits ...
For example: Having the SourceEnum.SABC flag called the SourceToDestMapper function three times, resulting in the following:
- SourceEnum.SA mapped to DestEnum.DA
- SourceEnum.SB mapped to DestEnum.DB
- SourceEnum.SC mapped to DestEnum.DC
And the result of DestEnum will be: DestEnum.DA | DestEnum.DB | DestEnum.DC