views:

2070

answers:

3

Hi,

I would like to have an explicit cast between from a string to an enum in c# in order to have this :

(MyEnum) Enum.Parse(typeof(MyEnum),stringValue)

I would like to deport this into an explicit cast operator, I did this but didn't work :

public static explicit operator (MyEnum)(value stringValue){
     return (MyEnum) Enum.Parse(typeof(MyEnum),stringValue);
}

Do you know if it's possible in c# ,net3.5?

Thanks in advance for your answer, Boris

+4  A: 

Is it necessary to use a cast operator? Another option would be to add an extension method off of string:

public static class StringEnumConversion
{
    public static T Convert<T>(this string str)
    {
        return (T)Enum.Parse(typeof(T), str);
    }
}
Andy
+5  A: 

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);
    }
}
Jason
A: 

hey Boris

You could also use "StringValue" attributes for get what you want.

Check out this question: stackoverflow.com/questions/424366/c-string-enums, there's plenty of info there that might help.

cheers

andy