Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# explicit cast string to enum

Tags:

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# using .NET 3.5?

like image 270
Boris Gougeon Avatar asked Jun 30 '09 00:06

Boris Gougeon


2 Answers

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)  {         Contract.Requires(typeof(T).IsEnum);         Contract.Requires(value != null);         Contract.Requires(Enum.IsDefined(typeof(T), value));         return (T)Enum.Parse(typeof(T), value);     } } 
like image 137
jason Avatar answered Sep 18 '22 16:09

jason


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);     } } 
like image 44
Andy Avatar answered Sep 22 '22 16:09

Andy