I would like to restrict the user to use any of the enumvalue.if the user tries to assign more than two values,i have to 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 validation.
Thanks, Lokesh
You can use Enum.IsDefined
to see whether an integral value is actually defined for an enum. In order to be able to detect that no logical operation such as Fruits.Apple | Fruits.Grapes
has been used make sure that 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 enum 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();
}
}
}
You can use the Enum.IsDefined()
method to check whether 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 incorrect: var f = Fruits.Apple&Fruits.Grapes
will assign Fruits.Apple
to f
. This is because a bitwise AND of Apple (==0) and Grapes (==2) will result in 0 (which still is a valid enum value -> Apple).
If you meant something like var f = Fruits.Orange|Fruits.Grapes
, then f will now be 3 (bitwise OR of 1 and 2) and Enum.IsDefined
will now return false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With