method takes any enum

essamce 621 Reputation points
2020-12-09T09:35:15+00:00

hi
how to get this functionality:

public static void GetEnum(string txt, out Enum result)
    {
          Enum.TryParse<value.GetType()>(txt, out value); // error
    }

thanks in advance

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,362 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andrea Angella 171 Reputation points MVP
    2020-12-09T09:53:41.99+00:00

    You can't use value.GetType() when you use a generics method. The generics type needs to determined at compile time.

    This means you need to make your method generics.

    public static void GetEnum<T>(string txt, out T result) where T : struct
    {
        Enum.TryParse(txt, out result);
    }
    

    The Enum.TryParse method only accepts types that are structs so you need to add a generic constraint (where T : struct) to make your code compile.

    I suggest you return the result instead of using out.

    public static T GetEnum<T>(string txt) where T : struct
    {
        Enum.TryParse(txt, out T result);
        return result;
    }
    

    So you can use your method like this:

    var result = GetEnum<MyEnum>("Value");
    
    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful