0

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?

sw1337
  • 533
  • 4
  • 16
  • You need to put it in a class. Can you just add the `using MyNamspace;` where you need to use it? – Trevor Aug 25 '20 at 00:57
  • Even if you do "MyEnum.One" it doesn't work. This value you need to parse is just the constant. You can't change that. – insane_developer Aug 25 '20 at 01:06
  • 1
    I'm only guessing but maybe the namespaces and containing class names are only visible to the compiler and not to the runtime. – sw1337 Aug 25 '20 at 01:59

2 Answers2

0

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);
Jeremy Lakeman
  • 9,515
  • 25
  • 29
  • 1
    I've tried your GetType idea but that didn't pan out (returns null). – sw1337 Aug 25 '20 at 02:16
  • Ah, right. That method works differently than I remembered (https://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null) – Jeremy Lakeman Aug 25 '20 at 02:18
0

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);
    }
}
mtreit
  • 789
  • 4
  • 6