How to check if an enumeration variable with a single enumeration value is assigned?

I would like to limit the user to use any of enumvalue. If the user tries to assign more than two values, I should throw an error.

public enum Fruits { Apple, Orange, Grapes } public Fruits Fruits { get { return m_fruits; } set { m_fruits=value; } } Fruits = Fruits.Apple & Fruits.Grapes; //I need to avoid such type of assignment 

Can anyone say how to check this type of check.

Thanks Lokesh

+4
source share
4 answers

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(); } } } 
+9
source

You can use the Enum.IsDefined() method to check if a value is a valid enum value:

 Fruits f1 = Fruits.Orange; Fruits f2 = (Fruits)77; var b1 = Enum.IsDefined(typeof(Fruits), f1); // => true var b2 = Enum.IsDefined(typeof(Fruits), f2); // => false 

BTW: Your example seems wrong: var f = Fruits.Apple&Fruits.Grapes will assign Fruits.Apple to f . This is because bitwise AND from Apple (== 0) and Grapes (== 2) will result in 0 (which is still a valid enum value -> Apple).

If you meant something like var f = Fruits.Orange|Fruits.Grapes , then f will now be 3 (bitwise OR from 1 and 2), and Enum.IsDefined will now return false.

+5
source

This is a bitwise operation and can only be used in conjunction with the [Flags] attribute, and when you values ​​for your enumeration are explicitly applicable to flags (for example, 1, 2, 4, 8, 16, etc. ..)

+1
source

You cannot limit it. The only way to do this is to create a custom class and create static fields with instances (like Encoding ). By the way, bitwise and meaningless for enum , which is not marked as [Flags] . Fruits.Apple&Fruits.Grapes will not set two values ​​( | does), this will lead to a meaningless result: since by default the enumerations are displayed in sequence from Fruits.Apple&Fruits.Grapes , you will get Fruits.Apple because Apple maps to 0

0
source

All Articles