Reputation:
I've searched and tried many things but I'm not really fully happy.
While converting an old project from VB.Net to C# I found that the behaviour between the 2 languages is very different and breaks the logic in C# if not dealt with.
Consider an enum like:
public enum TestEnum
{
Val1 = 1,
Val2 = 2
}
I have this code in VB.Net
// Will contain 1
txthMyHiddenField.Value = TestEnum1.Val1
And also
// Will contain ~/Something?var=1
Dim Url As String = "~/Something?var=" & TestEnum1.Val1
In C# this would have the first case having Val1
and on the second case "~/Something?var=Val1
"
The solution so far I could come up with without redesigning lots of code is to go everywhere and do something like:
= myEnum.ToString("d");
// Or
= ((int)myEnum).ToString();
// Or an extension.
I also considered creating an enum "class" but then I would have to change all switch statements, which is an even worse solution.
Am I missing something? Is there a cleaner way?
Upvotes: 1
Views: 253
Reputation: 1026
@Rivers,
I added a comment requesting more info in @Tim Schmelter's post but will try to provide a solution in the mean time.
@Eric, is correct in that it appears to come down to the explicit nature of C#. I also agree with @THG that if there is any change of repeatedly requiring this conversion, then an extension method is the cleanest way to go.
I haven't found a way to explicitly filter for enum, so I would be very interested in how such an extension method could be implemented.
In my case, I have limited type filtering and perform runtime validation. (I would obviously prefer compile time):
public static string ToIntString<T>(this T enumVal) where T : struct, IConvertible, IComparable, IFormattable
{
TestGenericEnum<T>();
return (Convert.ToInt32(enumVal).ToString();
}
private static void TestGenericEnum<T>()
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be of type System.Enum");
}
Update: Tossed in IComparable, IFormattable restrictions per @Preston's advice.
Update 2: Bone headed move, can't cast int directly, need to use Convert class.
Upvotes: 1
Reputation: 460340
Why not simply
var url = "~/Somethimg?var=" + (int)myEnum;
For what it's worth, maybe this extension helps:
public static class EnumExtensions
{
public static int AsInt<TEnum>(this TEnum enumType) where TEnum : struct, IConvertible
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an enum type");
return ((IConvertible)enumType).ToInt32(null);
}
}
var url = "~/Somethimg?var=" + myEnum.AsInt();
Upvotes: 5