The simplest way:
PriorityType tempPriority;
PriorityType? priority;
if (Enum.TryParse<PriorityType>(userInput, out tempPriority))
priority = tempPriority;
This is the best I can come up with:
public static class NullableEnum
{
public static bool TryParse<T>(string value, out T? result) where T :struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new Exception("This method is only for Enums");
T tempResult = default(T);
if (Enum.TryParse<T>(value, out tempResult))
{
result = tempResult;
return true;
}
result = null;
return false;
}
}
Use:
if (NullableEnum.TryParse<PriorityType>(userInput, out priority))
The above class can be used just like Enum.TryParse
except with a nullable input. You could add another overloaded function that takes a non-nullable T
so that you could use it in both instances if you want. Unfortunately extension methods don't work very well on enum types (as far as I could try to manipulate it in the short time I tried).
PriorityType
and then assign it topriority
after you parse it? – PlasticizeTEnum
generic parameter is setup aswhere TEnum: struct
. – Agateware