patterncsharpMinor
Parsing from one enum to another
Viewed 0 times
enumoneparsinganotherfrom
Problem
I face a problem I think I am not approaching appropiately.
I have two independent enumerators that both will contain the same members, the only difference being the values given.
I have to be able to parse from one enum type to the other on the fly and I've seen the following code works as intended:
But I feel like there's something I am doing wrong, I believe this code is prone to errors and I feel like I need some help approaching this problem.
The code involved is the following:
Again, this code works as intended, I can convert from one enum to the other, but I feel there's something wrong with it.
I have two independent enumerators that both will contain the same members, the only difference being the values given.
I have to be able to parse from one enum type to the other on the fly and I've seen the following code works as intended:
(enumType)Enum.Parse(typeof(enumType), enum1.ToString());But I feel like there's something I am doing wrong, I believe this code is prone to errors and I feel like I need some help approaching this problem.
The code involved is the following:
public enum AdjustCircuitsCurrent
{
_2V = 0x0001,
_1_28V = 0x0002,
_333mV = 0x0003,
_0_25A = 0x0004,
_0_01V = 0x0005,
_0_1V = 0x006,
_1V = 0x0007,
}
public enum VerificacionCircuitsCurrent
{
_2V = 0x000B,
_1_28V = 0x000C,
_333mV = 0x000D,
_0_25A = 0x000E,
_0_1V = 0x00F,
_0_01V = 0x0011,
_1V = 0x0012,
}
public VerificacionCircuitsCurrent ConvertToVerificationCircuit(AdjustCircuitsCurrent circuit)
{
return (VerificacionCircuitsCurrent)Enum.Parse(typeof(VerificacionCircuitsCurrent), circuit.ToString());
}Again, this code works as intended, I can convert from one enum to the other, but I feel there's something wrong with it.
Solution
There's nothing particularly wrong with the code. It happens often enough that this question has plenty of upvotes.
Marc Gravell gives the exact code that you have. But you can go take a look at the link for ideas about using extension methods to make calling the conversion nicer and possibly adding an "IsDefined" check in case the enums get out of sync sometime in the future.
Marc Gravell gives the exact code that you have. But you can go take a look at the link for ideas about using extension methods to make calling the conversion nicer and possibly adding an "IsDefined" check in case the enums get out of sync sometime in the future.
Context
StackExchange Code Review Q#112417, answer score: 3
Revisions (0)
No revisions yet.