Contraining the parameter to a specializedEnum?

Oct 14, 2009 at 1:01 PM

Hi there,

Great utility, but i found an issue with what i need to do and don't know if i am missing something i a signature on a method like so, actually its an extension method but that doesn't matter.

public static IQueryable<Vehiculo> WithStatus(this IQueryable<Vehiculo> qry, VehicleStatuses vehicleStatus)

Problem being in that i want to pass in for example    .WithStatus(VehicleStatuses.Available) but it of course complains because i am now passing in a string ...

 

Now I could change the signature to string vechicelStatus  but that means that the parameter is no longer contrained to items within type VehicleStatuses  hence i can pass in "I am an invalid status that doesn't exist) and it works

 

Any ideas?

 

Thanks

 

 

Coordinator
Jun 12, 2010 at 8:08 PM

I've been mulling it over. The problem is that enums have special behaviors that are difficult to emulate in that regard. Presumably, it may be possible to restate the problem in such a way that the individual items are derived from a base class and restrict them that way, but this is definitely non-trivial. I've had a number of projects going and thus little time to work (or even look at) SpecializedEnum in quite a while. If I have the time and a solution occurs to me, I'll post it. I hope you were able to work around this ok. I know compile-time type safety would be better, but perhaps you could make use of the Parse function in the meantime and enforce it at runtime?

Coordinator
Jun 12, 2010 at 8:17 PM

Oh, also, a TryParse implementation to help with that wouldn't be too hard.

    public static TValues Parse(string name)
    {
        if (keyValuePairs.ContainsKey(name))
        {
            return keyValuePairs[name];
        }
        else
        {
            throw new ArgumentException("name", "The value provided was invalid.");
        }
    }

 

    public static bool TryParse(string name, out TValues result)
    {
        if (keyValuePairs.ContainsKey(name))
        {
            result = keyValuePairs[name];
            return true;
        }
        else
        {
            result = default(TValues);
            return false;
        }
    }