Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, StringToEnum, can I make it a generic function out of this

Tags:

c#

I'd like to have a simple helper method for converting a string to an Enum. Something like the following, but it doesn't like T as the first argument in the Enum.Parse. The error is T is a Type Parameter but is used like a variable.

public static T StringToEnum<T>(String value)
        {
            return (T) Enum.Parse(T,value,true) ;
        }
like image 728
jeff Avatar asked Jan 23 '23 18:01

jeff


2 Answers

Try this:

public static T StringToEnum<T>(String value)
{
     return (T)Enum.Parse(typeof(T), value, true);
}
like image 178
Tamas Czinege Avatar answered Jan 30 '23 08:01

Tamas Czinege


public static T StringToEnum<T>(String value)
{
    return (T) Enum.Parse(typeof(T),value,true) ;
}

What you were doing is like using 'int' as a Type, but it is not a Type object. To get the Type object, you would use typeof(int).

like image 26
Ed S. Avatar answered Jan 30 '23 09:01

Ed S.