You can use Enum.IsDefined to determine if an integer value is really defined for an enumeration. So that you can detect that a logical operation was not used, for example Fruits.Apple | Fruits.Grapes Fruits.Apple | Fruits.Grapes , make sure your enum values ββare flags.
public enum Fruits { Apple = 1, Orange = 2, Grapes = 4 } public Fruits Fruit { get { return m_fruits; } set { if (!Enum.IsDefined(typeof(Fruits), value)) { throw new ArgumentException(); } m_fruits = value; } }
Update:
A faster method without reflection would be to check all the enumeration values ββyourself:
public Fruits Fruit { get { return m_fruits; } set { switch (value) { case Fruits.Apple: case Fruits.Grapes: case Fruits.Orange: m_fruits = value; break; default: throw new ArgumentException(); } } }
source share