I’m aware of Enum.TryParse(), but it doesn’t handle the namespace and type being present in the string. Say I have the following enum:
namespace MyNamespace
{
enum MyEnum
{
One,
Two,
Three
}
}
I can’t use Enum.TryParse("MyNamespace.MyEnum.One", out MyEnum xxx). It returns false because “MyNamespace.MyEnum.One” is not recognized.
Enum.TryParse("One", out MyEnum xxx) works fine.
Is there a way I can do that with any other mechanism in .Net?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
One simple approach would be to write a small utility method to just parse the token after the last period character:
public static class EnumHelper
{
public static bool TryParse<TEnum>(
string value,
out TEnum result) where TEnum : struct
{
string toparse = value;
int loc = value.LastIndexOf('.');
if (loc > 0)
{
toparse = value.Substring(loc + 1);
}
return Enum.TryParse(toparse, out result);
}
}
Method 2
Enum.TryParse expects you to know which type of enum you are expecting;
Enum.TryParse(typeof(MyEnum), "One", out var value);
You could try to parse a type from a string first;
var type = Type.GetType("MyNamespace.MyEnum");
Enum.TryParse(type, "One", out var value);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0