0

Here's what I want to do

string MyEnumType = "SpaghettiDiameter";
string MyEnumValue = "NEEDS_ALL_SAUCE";


//this is not exact syntax - only to represent the logic
//MyEnumValue is converted from string to the type contained in MyEnumType
var Dinner = Convert(MyEnumValue, MyEnumType);

The convert function would need to know how to get from what's in MyEnumType to an actual, declared enum, and would work for any type passed. Compile time conversions would not be possible.

EDIT: I want to create a function "Convert" that will accept two strings - a string naming the enumerated type and a string of the enumerated value. It would not be specific to any given enumerated type. The function would return the enumerated value to a variable of that type.

Is this doable or am I just dreaming?

Chuck Bland
  • 255
  • 1
  • 2
  • 13
  • 3
    How about `Enum.Parse`? Probably with `GetType` for the type argument if you really want that one to be a string – BradleyDotNET Jun 14 '17 at 19:16
  • To add to @BradleyDotNET 's comment, here it is [straight from the docs](https://msdn.microsoft.com/en-us/library/essfb559(v=vs.110).aspx) – maccettura Jun 14 '17 at 19:18
  • My understanding of the Parse method is that the type info is handled at compile time, and the prototype in the docs does not show this arg as type string. Do I have that right? – Chuck Bland Jun 14 '17 at 19:54

2 Answers2

0

If you can supply the fully qualified namespace of the enum, you can use Enum.Parse as mentioned.

public enum SpaghettiDiameter
{
    Value1,
    NEEDS_ALL_SAUCE
}
class Program
{
    static void Main(string[] args)
    {
        string MyEnumType = "TestAppCore.SpaghettiDiameter";
        string MyEnumValue = "NEEDS_ALL_SAUCE";
        SpaghettiDiameter result = (SpaghettiDiameter)Enum.Parse(Type.GetType(MyEnumType), MyEnumValue);
    }
}
Ryan Fleming
  • 189
  • 7
0

I'm dreaming. I don't think what I described in the edit is doable.

Chuck Bland
  • 255
  • 1
  • 2
  • 13