2

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)

3 Answers 3

6

Make the generic method generic:

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

Usage:

OtherEnumType result = ConvertStringToAnEnum<OtherEnumType>("TEST1_");
Sign up to request clarification or add additional context in comments.

8 Comments

you were faster, +1 for you :)
Important: It's not type safe because T is not required to be a enum.
Maybe Enum.TryParse would be a better option?
@FelixK. I will use the function as private...The function won't be public
@FelixK.: Not strictly true. It's type safe, but not strictly typed. Using it with a non enum gives you an exception. Besides Enum.Parse(typeof(int), "asdf") also compiles just fine...
|
2

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>();

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.