The system have a plain enum like this,
public enum SomeEnum : short
{
Ok = 0,
Missing = 17,
};
This enum are now into a situation where I need to mask some more information into it without change the appearence of the existing enum values. The enum will got some new values,
[Flags]
public enum SomeEnum : short
{
Ok = 0,
Missing = 17,
Blocking = 18, // Values could be anything
Low = 19, // Values could be anything
};
I was afraid there could be problem to the current enum usage. It appears that I’m right, but I hope i’m proved wrong with your help. The usage until today are built around SomeEnum.Ok. Also tomorrow, but the Ok need additional info. I need to mask the enum values without affect it’s current behavior, which could came from any common reference;
someEnumVariable.ToString()
(int)someEnumVariable
someVar = SomeEnum.Ok
Enum.Parse(typeOf(SomeEnum), someString)
If I flag the enum with
var test = (SomeEnum.Ok | SomeEnum.Blocking);
Both flags can be founded i.e. test.HasFlags(SomeEnum.Ok) or test.HasFlags(SomeEnum.Blocking) but the enum represents as SomeEnum.Blocking, which aren’t possible.
Any ideas?
Because the value of
SomeEnum.OKis 0, callingHasFlag(SomeEnum.OK)will always return true. When you mask enums together, the process relies on the fact that the sum of any combination of enum values will be unique. Typically you would set these up starting using values of2^0,2^1,2^2, etc. For example:If you want to mask the values together, you’ll have to use the
Flagsattribute. If you can’t refactor and change the value ofSomeEnum.OK, then you may have to rely on passing in aSomeEnum[], rather than a single maskedSomeEnumvalue.EDIT
Just a quick note on masking the values together using the enum defined above. Take the following code:
When these items are OR’ed together, .NET just adds the values together to produce a new, unique value that represents the combination of the OR’ed items. Using enum values that are powers of 2 ensures that the combinations will always be unique.