Sunday, April 3, 2011

how do I create an enum from a string representation? c#

im trying to pass back from a user control a list of strings that are part of an enum, like this:

<bni:products id="bnProducts" runat="server" ProductsList="First, Second, Third"  />

and in the code behid do something like this:

public enum MS 
    {
     First = 1,
     Second,
     Third
    };
    private MS[] _ProductList;
    public MS[] ProductsList
    {
     get
     {
      return _ProductList;
     }
     set
     {
      _ProductList = how_to_turn_string_to_enum_list;
     }
    }

my problem is I dont know how to turn that string into a list of enum, so what should be "how_to_turn_string_to_enum_list"? or do you know of a better way to use enums in user controls? I really want to be able to pass a list that neat

From stackoverflow
  • You need to look at the System.Enum.Parse method.

    Best Regards

    Ayyash : this one "or"s the values passed, not what im looking for
    Oliver Hanappi : What do you mean exactly? Of course this method just converts one single value to an Enum, you need to loop through all and apply the method on each element ;)
  • string[] stringValues = inputValue.Split(',');
    
    _ProductList = new MS[stringValues.Length];
    
    for (int i=0;i< stringValues.Length;i++)
      _ProductList[i] = (MS) Enum.Parse(typeof(MS), stringValues[i].Trim());
    

    (updated my code because I misread your code)

  • Enum.Parse is the canonical way to parse a string to get an enum:

    MS ms = (MS) Enum.Parse(typeof(MS), "First");
    

    but you'll need to do the string splitting yourself.

    However, your property is currently of type MS[] - the value variable in the setter won't be a string. I suspect you'll need to make your property a string, and parse it there, storing the results in a MS[]. For example:

    private MS[] products;
    
    public string ProductsList
    {
        get
        {
            return string.Join(", ", Array.ConvertAll(products, x => x.ToString()));
        }
        set
        {
            string[] names = value.Split(',');
            products = names.Select(name => (MS) Enum.Parse(typeof(MS), name.Trim()))
                            .ToArray();
        }
    }
    

    I don't know whether you'll need to expose the array itself directly - that depends on what you're trying to do.

    Hans Kesting : eh, Enum.Parse needs a Type if I am not mistaken? MS ms = (MS)Enum.Parse(typeof(MS), "First");
    Jon Skeet : Oops, thanks :)
    Ayyash : you're right, it sould be a string, i would combine this answer with "280Z28" answer above because i think the CovertAll is more elegent, thanks
  • This is a short solution, but it doesn't cover some very important things like localization and invalid inputs.

    private static MS[] ConvertStringToEnumArray(string text)
    {
        string[] values = text.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
        return Array.ConvertAll(values, value => (MS)Enum.Parse(typeof(MS), value));
    }
    
    Jon Skeet : +1 for validation. From the example, localization isn't much of an issue because this isn't user-supplied data - it's in the page code.
  • Mark your enum with the [Flags] attribute, and combine flags instead of an array of enum values.

    Jon Skeet : That's not always valid. For instance, HTTP response codes aren't *logically* flags - but you might have a collection of them (e.g. "I handle these response codes"). Don't rush to use flags for enums which aren't logically flags.

0 comments:

Post a Comment