0

Example:

class foo
{
    byte val = 3;
    string EnumName = "boo";

    Enum boo : byte
    {
        coo = 1,
        doo = 2,
        hoo = 3
    }

    Enum boo2 : byte
    {
        eoo = 3,
        goo = 8
    }
}

How can I do something like this:

Console.WriteLine((GetEnum(EnumName)value).ToString()); // GetEnum is not real

The EnumName will change everytime.

Expected Output:

When Enum Name is boo == "hoo"

When Enum Name is boo2 == "eoo"

Edit: I am going to use this for logging:

Message to boo2.goo

Message to boo.coo

Message to boo.doo

6
  • 1
    I don't understand your code. What is the purpose of an enum with only 1 element in it? Commented Jul 23, 2013 at 0:05
  • Check out Type.GetType and use reflection to get the underlying value, though that will have to be done using a string as it's not a compile time constant. Commented Jul 23, 2013 at 0:09
  • The problem in the code you wrote is the .shoo after GetEnum(EnumName) because .NET is statically-typed (except with the new dynamic keyword introduce with C# 4.0). It means that the compiler has to know what type is returned by GetEnum() and this type has to declare a member called shoo. Commented Jul 23, 2013 at 0:10
  • I have updated the Code. I am trying to Log some Bytes(Message) which are converted to get the Enum names. @Matthew It may not work when Assembly is Obfuscated. Commented Jul 23, 2013 at 0:15
  • I think there's something horribly wrong with your design. Commented Jul 25, 2013 at 20:40

2 Answers 2

1

Use (EnumType) Enum.Parse("boo", typeof(EnumType));

Sign up to request clarification or add additional context in comments.

1 Comment

It will not work as I do not know the EnumType. It's the EnumType I am trying to find.
0

If you want to get a type based on the string you could search your whole application domain for the available types and you could check if the type is an enumeration as well as if the name suites. After you have the right type you should be able to get the values / names, whatever you want. Maybe this solution is a little bit like a hammer, but I think it works for your case. (I dont know how your application is structured).

var domain = AppDomain.CurrentDomain;
var assemblies = domain.GetAssemblies();
foreach(var assembly in assemblies)
{
    foreach(Type t in assembly.GetTypes())
    {
        string name = t.Name; // or t. Fullname if you know it
        // you can also check if the type is an Enum, etc...
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.