Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify allowed enum values in a property

Is it possible to specify that a enum property can only have a range of values?

enum Type
{
    None,
    One,
    Two,
    Three
}

class Object
{
    [AllowedTypes(Type.One,Type.Three)]
    Type objType { get; set; }
}

Something like this? Maybe some validator in enterprise library that I don't know of ?!

Ty

like image 687
Hélder Gonçalves Avatar asked May 15 '14 13:05

Hélder Gonçalves


People also ask

Can we assign value to enum?

You can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially.

Can you inherit enums?

Inheritance Is Not Allowed for Enums.

Can enums have properties Java?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can I declare enum in class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.


1 Answers

You could do the validation in setter logic.

EDIT: some example:

class Object
{
    private Type _value;

    public Type objType{ 

        get{ return _value; }
        set{
            if(value != Type.One && value != Type.Three)
                throw new ArgumentOutOfRangeException();
            else
                _value = value;
        }
    }
}
like image 65
st4hoo Avatar answered Sep 30 '22 06:09

st4hoo