J.D. Ray
J.D. Ray

Reputation: 727

How to limit a string to a set of dynamically-defined values?

I have a class that has a string property for which I'd like to limit the possible values to a set defined dynamically (e.g. stored in the database, though we're using code-first EF6). Using an Enum is obviously out. I did some reading about Code Contracts and like the look of that, but don't know the first thing about establishing a Contract.Requires that pulls back a set of values. Lambda, maybe? I'm on the bleeding edge of my understanding here.

Here's some sample code:

public class Rule
{
    /// <summary>The Conditions associated with this Rule
    /// </summary>
    public ICollection<Condition> Conditions { get; set; }

    // ... some other stuff ...

    /// <summary>The Status of the Rule.
    /// </summary>
    public string RuleStatus 
    { 
    get{}
    set
    {
        // Here's where I want to dynamically determine values
        Contract.Requires(value == "Inactive"||"Obsolete");
        // Perhaps something like this, 
        // where GetValidRuleStatuses returns an array of string??
        Contract.Requires(GetValidRuleStatuses().Contains(value));
    }
}

Upvotes: 1

Views: 333

Answers (1)

Dave Bish
Dave Bish

Reputation: 19646

One way to do this, is to write custom code to actually perform the check as and when you need to.

In terms of data structures, I'd recommend a HashSet<string> for fast lookups, which you will need to populate:

//Cache this somewhere, until the values change
var allowedValues = new HashSet<string>(stringValues);

if(!allowedValues.Contains(attemptedValue))
{
    //Throw exception?
}

Upvotes: 2

Related Questions