1

Non Generic Version (works):

    eTargets ParseTargets(string input)
    {
        eTargets targets = eTargets.None;
        string[] items = input.Split(',');
        foreach (var item in items)
        {
            eTargets target;
            if (Enum.TryParse(item, out target))
            {
                targets |= target;
            }
            else
            {
                Logger.LogError("invalid target: " + item);
            }
        }
        return targets;
    }

Attempt at generic version (does not compile):

    T ParseNames<T>(string delimitedNames) where T : struct
    {
        T result = default(T);
        foreach (var name in delimitedNames.Split(','))
        {
            T parsed;
            if (Enum.TryParse<T>(name, out parsed)) 
                result |= (int)parsed; // ERROR: cannot convert T to int
                // result |= parsed --> operator |= cannot be applied to T and int
        }
        return (T)result;
    }

If the answer is "no", it would be helpful to understand the underlying limitation.

Aaron Anodide
  • 16,906
  • 15
  • 62
  • 121

2 Answers2

2

How about

T ParseNames<T>(string delimitedNames) where T : struct //, Enum
{
    return (T) Enum.Parse(typeof(T), delimitedNames);   
}

Your code already implies a 1, 2, 4, 8 numbering so the only 'gap' here is the requirement for the [Flags] attribute

H H
  • 263,252
  • 30
  • 330
  • 514
  • `Enum` is not a valid constraint on a type parameter. – vcsjones Jan 11 '12 at 16:49
  • yea, I fixed it in my question - sorry about that – Aaron Anodide Jan 11 '12 at 16:51
  • @Henk, yes the base 2 thing is implied, i should rename it ParseFlags – Aaron Anodide Jan 11 '12 at 16:51
  • 1
    you are telling me it's a built in feature that i'm trying to re-write here? – Aaron Anodide Jan 11 '12 at 16:52
  • @Gabriel I just learned that as well, but yes: `The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants delimited by commas (,). One or more blank spaces can precede or follow each value, name, or comma in value. If value is a list, the return value is the value of the specified names combined with a bitwise OR operation.` http://msdn.microsoft.com/en-us/library/essfb559.aspx – vcsjones Jan 11 '12 at 16:54
  • @Gabriel: Yes, I was wondering if this was 'just for fun' or that you missed it. – H H Jan 11 '12 at 16:56
1

This should work:

static T ParseNames<T>(string delimitedNames) where T : struct
{
    int result = 0;
    foreach (var name in delimitedNames.Split(','))
    {
        result |= (int)Enum.Parse(typeof(T), name);
    }
    return (T)(object)result;
}
vgru
  • 49,838
  • 16
  • 120
  • 201