A cast is not possible. The issue is that a user-defined conversion must be enclosed in a struct or class declaration, and the conversion must be to or from the enclosing type. Thus,
public static explicit operator MyEnum(string value)
is impossible because neither MyEnum nor string can ever be the enclosing type.
The relevant section of the ECMA334 C# spec is 17.9.4:
A conversion operator converts from a source type, indicated by the parameter type of the conversion
operator, to a target type, indicated by the return type of the conversion operator. A class or struct is
permitted to declare a conversion from a source type S to a target type T only if all of the following are true,
where S0 and T0 are the types that result from removing the trailing ? modifiers, if any, from S and T:
S0 and T0 are different types.
Either S0 or T0 is the class or struct type in which the operator declaration takes place.
Neither S0 nor T0 is an interface-type.
Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.
However, you can do an extension method on the string class.
public static class StringExtensions {
public static T ConvertToEnum<T>(this string value) {
if (typeof(T).BaseType != typeof(Enum)) {
throw new InvalidCastException();
}
if(Enum.IsDefined(typeof(T), value) == false) {
throw new InvalidCastException();
}
return (T)Enum.Parse(typeof(T), value);
}
}