Reputation: 46222
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;
}
}
Upvotes: 0
Views: 146
Reputation: 217243
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)
Upvotes: 2