It is well known fact that Enum.TryParse does not exist in .net 3.5 although it is available in 4.0
There have been some previous implementations already made here, here and here. I thought I should add my $0.02 into the mix & put out my own implementation, so here goes:
Note: line breaks added for clarity & to fit the layout
public static class Extensions{
public static bool TryParse<T>(this T enum_class,
string value, out T result){
return Extensions.TryParse(enumClass, value, true,
out result);
}
public static bool TryParse<T>(this T enum_class,
string value,
bool ignoreCase, out T result)
where T : struct
// cannot constraint by System.Enum type
{
result = default(T);
var is_converted = false;
var is_valid_value_for_conversion = new Func<T,
object, bool, bool>[]{
(e, v, i) => e.GetType().IsEnum,
(e, v, i) => v != null,
(e, v, i) => e.GetType().IsEnum,
(e, v, i) => Enum.GetNames(e.GetType()).Any(
n => String.Compare(n, v.ToString(), i) == 0
|| (v.ToString().Contains(",")
&&
v.ToString().ToLower()
.Contains(n.ToLower())))
|| Enum.IsDefined(e.GetType(), v)
};
if(is_valid_value_for_conversion.All(
rule => rule(enum_type, value, ignoreCase))){
result = (T)Enum.Parse(typeof(T),
value.ToString(), ignoreCase);
is_converted = true;
}
return is_converted;
} }
This code currently can convert the following:
| Enum | Converted from |
|---|---|
|
“A” or “a” |
|
“A” or “a” or 1 |
|
“A” or “a” or “A, B” or “A, b” or “a, B” or “a, b”, 1 |
Drop a note if you find this useful.