c# - How to combine enumerations with flags? -
i have enumeration flags. want declare variable n different flags. n > 1 in case.
public enum biometype { warm = 1, hot = 2, cold = 4, intermediate = 8, dry = 16, moist = 32, wet = 64, } okay - 1 variant cast each flag byte , cast result enum.
biometype btype = (biometype)((byte)biometype.hot + (byte)biometype.dry) but kinda messy - imho. is there more readable way combine flags?
simple, use binary "or" operator:
biometype btype = biometype.hot | biometype.dry; also, if values can combined it's best mark enum flags attribute indicate this:
[flags] public enum biometype { warm = 1, hot = 2, cold = 4, intermediate = 8, dry = 16, moist = 32, wet = 64, } adding enumeration values bad number of reasons. makes easy produce value outside defined values, i.e.:
biometype btype = (biometype)((byte)biometype.wet + (byte)biometype.wet); while contrived, example yields value of 128, doesn't map known value. still compile , run, it's didn't build code handle values outside of defined , lead undefined behavior. however, if use pipe (or "binary or") operator:
biometype btype = biometype.wet | biometype.wet; the result still biometype.wet.
furthermore, using addition in question provides no intellisense in ide makes using enumeration unnecessarily more difficult.
Comments
Post a Comment