Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an enum variable is assigned with a single enum value?

Tags:

c#

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

like image 441
Lokesh Avatar asked Dec 08 '22 01:12

Lokesh


2 Answers

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();
        }
    }
}
like image 129
Dirk Vollmar Avatar answered Jan 04 '23 23:01

Dirk Vollmar


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.

like image 42
M4N Avatar answered Jan 04 '23 23:01

M4N