I'm trying to take some json input and parse into the correct enum type. I have 3 Enum types:
public class Enums
{
public enum Motivators{
Small_Motivator,
Medium_Motivator,
Large_Motivator
}
public enum Reactors{
Small_Reactor,
Large_Reactor
}
public enum Movers{
Small_Mover,
Large_Mover
}
}
private void InitializeGenerator(Enum enumType)
{
if (enumType is Enums.Motivators)
{
// work work work work work
}
else if (enumType is Enums.Reactors)
{
// work
}
else if (enumType is Enums.Movers)
{
// work
}
else
{
// we dont know what it is
}
}
{
"WorkerType":"Small_Motivator"
}
JObject jObject = JObject.Parse(json);
JToken worker = jObject.GetValue("WorkerType");
Enum workerType = (Enum)Enum.Parse((typeof(Enum)), worker.ToString(), true);
InitializeGenerator(workerType);
An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code
Additional information: Type provided must be an Enum.
You can easy parse string to your enum instance. But you should define enum types
static void Main(string[] args)
{
string worker = "Small_Motivator";
var provider = new EnumProvider();
var enumValue = provider.GetByValue(worker);
}
public class EnumProvider
{
public object GetByValue(string sourceStr)
{
var enumTypes = new[]
{
typeof(Enums.Motivators),
typeof(Enums.Movers),
typeof(Enums.Reactors)
};
foreach (var type in enumTypes)
{
var enumValues = Enum.GetValues(type)
.Cast<object>()
.Select(x => x.ToString())
.ToArray();
if (enumValues.Any(x => x == sourceStr))
{
return Enum.Parse(type, sourceStr);
}
}
throw new ArgumentException($"{sourceStr} not supported");
}
}