views:

162

answers:

3

I am parsing some enum values from a text file. In order to simplify things I am using functions like the following:

(The sample code here uses C++/CLI but answers in C# are also welcome.)

bool TryParseFontStyle(String ^string, FontStyle% style){
    try {
     FontStyle ^refStyle = dynamic_cast<FontStyle^>(
      Enum::Parse(FontStyle::typeid, string));
     if(refStyle == nullptr)
      return false;
      style = *refStyle;
     return true;
    }
    catch(Exception ^e){
     return false;
    }
}

Now I need to rewrite similar functions for each enum type that I am parsing. How do I use generics to write one single function to handle any enum type?

Update: Found a similar question here: How to TryParse for Enum value?

A: 

This method seems to work and does not use try/catch.

public static bool EnumTryParse<T>(string strType,out T result)
{
    string strTypeFixed = strType.Replace(' ', '_');
    if (Enum.IsDefined(typeof(T), strTypeFixed))
    {
        result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
        return true;
    }
    else
    {
        foreach (string value in Enum.GetNames(typeof(T)))
        {
            if (value.Equals(strTypeFixed, StringComparison.OrdinalIgnoreCase))
            {
                result = (T)Enum.Parse(typeof(T), value);
                return true;
            }
        }
        result = default(T);
        return false;
    }
}

Source

Espo
+1  A: 
public static bool TryParseEnum<T> (string value, out T result) where T : struct
{
    if (value == null)
    {
        result = default (T) ;
        return false ;
    }

    try
    {
        result = (T) Enum.Parse (typeof (T), value) ;
        return true  ;
    }
    catch (ArgumentException)
    {
        result = default (T) ;
        return false ;
    }
}
Anton Tykhyy
Thanks. This is what I was looking for. Is there any way I can restrict T to be an Enum derivative?
Vulcan Eager
No, there isn't.
Anton Tykhyy
A: 

In c#:

Enum.Parse(typeof(yourEnum),"yourValue");

Just surround that with a try catch and your set to go

Sergio
Actually Enum.Parse(typeof(yourEnum), "yourValue");
Alfred Myers
That is correct, thanks ;)
Sergio