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
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
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");