Create function which parse an Enum in C#

I know that to parse a string to specific enum like:

enum AnEnumType 
{
   TEST_,
   OTHER_TEST_,
   OTHERS_
}

enum OtherEnumType 
{
   TEST1_,
   OTHER_TEST1_,
   OTHERS1_
}


string aValueString = "TEST_";

AnEnumType result = (AnEnumType)Enum.Parse(typeof(AnEnumType), aValueString);

So, I want to create a function, a generic one which use parser for my enum(s) like:

public Type ConvertStringToAnEnum(string value, Type anyType){

return (anyType)Enum.Parse(typeof(anyType), aValueString);
}

But I guess that is not OK...

How to make the function which parse any enumeration type specified as argument in function?

like I want to call OtherEnumType result = ConvertStringToAnEnum("TEST1_", OtherEnumType)

Answers


Make the generic method generic:

public T ConvertStringToAnEnum<T>(string value){
  return (T)Enum.Parse(typeof(T), value);
}

Usage:

OtherEnumType result = ConvertStringToAnEnum<OtherEnumType>("TEST1_");

You could try to use

public T ConvertStringToAnEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value);
}

With this you can do OtherEnumType tp2 = ConvertStringToAnEnum<OtherEnumType>("TEST1_");

or using an extension method

public static class Extensions
{
    public static T ToEnum<T>(this string value)
    {
        return (T)Enum.Parse(typeof(T), value);
    }
}

With this you can do

OtherEnumType tp2 = "TEST1_".ToEnum<OtherEnumType>();

Depending on how involved you want to get, you can also use attributes to give your enum values more descriptive names. Associating Strings with enums in C# gives a pretty good intro in how to do this.


Need Your Help

embedding an application within a c# program with gtk#

c# gtk embed gtk#

I'd like to embed a movie watching application like VLC into my C# program using the GTK# binding.