Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict a variable to a fixed set of strings?

Tags:

c#

If I want to restrict the values of the spicelevel column in the database to 1, 2 and 3, I could do something like

    private enum SpiceLevel
    {
        Low=1,
        Medium=2,
        Hot=3
    }

Then in the code I could do (int)SpiceLevel.Low to pick 1 as the spice level.

Now what if I have a need where I can only accept "Red Rose","White Rose" and "Black Rose" for the values of a column in the database? What is a graceful way to handle this?

I am thinking of storing them in a config file or constants, but neither is as graceful as enums. Any ideas?

Update:

The answer here worked for me

like image 208
Foo Avatar asked Aug 15 '13 23:08

Foo


1 Answers

You can use a property for this

public string[] AllowedRoses = new string[] {  "Red Rose", "White Rose" ,"Black Rose" };
string _Rose = "Red Rose";
public string Rose
{
    get
    {
        return _Rose;
    }
    set
    {
        if (!AllowedRoses.Any(x => x == value)) 
               throw new ArgumentException("Not valid rose");
        _Rose = value;
    }
}
like image 75
I4V Avatar answered Sep 29 '22 01:09

I4V