user420667
user420667

Reputation: 6700

Parsing user provided enumeration values in C#

I'd like for the user to provide an enum name, say "Color", and a value, say "red", and tell them whether or not that is a member value of that enumeration, or if the enumeration even exists.

How can I do this?

In the past, I have used Type.GetType("UserProvidedType").Parse / Convert.ChangeType, but this doesn't appear to work when the user provided type is an enumeration. Please see: Parsing to primitive types, based on user input in c# for past solutions that don't appear to work in this context.

Thanks.

Upvotes: 1

Views: 136

Answers (1)

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

var type = Type.GetType("YourNameSpace.Color");
var belongs = Enum.GetNames(type).Any(o => o == "Red");

Upvotes: 6

Related Questions