0

I have the following code which does not work but you can get an idea of what I am trying to do. I am not sure how to get a string based on the Enum. I am passing the Enum Name to the Method:

   class StateInfo
    {
        enum State{ Illinois= 0, Ohio= 1, Indiana= 2, Michigan= 3, Conneticut= 4 }; 

        static void Main(string[] args)

        {
            string result = ConvToJson("State");

        }


        public static string ConvToJson(string enumName)
        {

           Type e = Enum.GetName(typeof(enumName));

          var ret = "{";

          foreach (var val in Enum.GetValues(e))
          {
             var name = Enum.GetName(e, val);
            ret += name + ":" + ((int)val).ToString() + ",";
          }

        ret += "}";

        return ret;
     }

 }

1 Answer 1

2

You can use the Type.GetType Method to get the Type from a string specifying the type's name:

Type e = Type.GetType(enumName);

The name must specify the full namespace and, if the type is not in the currently executing assembly or in Mscorlib.dll, also the assembly name:

string result = ConvToJson("MyNamespace.StateInfo+State");
string result = ConvToJson("MyNamespace.StateInfo+State, MyAssembly, " +
    "Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089");

It might be easier to pass the type directly to the method:

string result = ConvToJson(typeof(State));
public static string ConvToJson(Type e)
Sign up to request clarification or add additional context in comments.

1 Comment

Hello, based on string result = ConvToJson("MyNamespace.State"); I have a situation where Type e = Type.GetType(enumName); is null though. I substituted MyNamespace with a valid namespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.