How to restrict a variable to a fixed set of strings?
c#
Solution
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;
}
}
Problem
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