More reasons never to use C# enums
Tuesday, January 20th, 2004I already hate c# enums, for reasons I have expounded on before. But I just found another doozy. Suppose I have an enum defined as follows:
public enum AnEnum
{
One = 1,
Two = 2
}
What do you think would happen if I tried to do this:
int illegalValue = 666;
AnEnum shouldBeIllegal = (AnEnum)illegalValue;
Console.WriteLine(string.Format("Value is : {0}", shouldBeIllegal));
Console.WriteLine(string.Format("Type is : {0}", shouldBeIllegal.GetType()));
I would expect an Exception of some sort - probably some kind of cast exception.So what happens? It works! C# and .NET will let you create a “strongly typed” enum with an underlying int value of 666, or anything you like.. Now that’s just insane. It also gives me another reason to prefer the Java style strongly typed enums.
Here’s the complete code I used to prove this:
using System;
using NUnit.Framework;
namespace EnumIsBroken{
public enum AnEnum{One = 1,Two = 2}
[TestFixture]
public class EnumTests{
[Test]
public void BrokenEnumBehaviour()
{
int illegalValue = 666;
AnEnum shouldBeIllegal = (AnEnum)illegalValue;
Console.WriteLine(string.Format("Value is : {0}", shouldBeIllegal));
Console.WriteLine(string.Format("Type is : {0}", shouldBeIllegal.GetType()));
}
[Test]
public void NormalBehaviour()
{
AnEnum one = (AnEnum)1;
Assertion.AssertEquals(AnEnum.One, one);
}
}
}







