Crazy Enums

By gauravsharma82

There is one intresting thing that I want to share. Almost all of us have worked with .Net Enums. Let me show you something,
Create a project and add one Enum to it,
enum MyEnum
{
  Orange=0,
  Red=1,
  Green=2
}

Now create another class where we will use this Enum,
class Program
{
  static void Main(string[] args)
  {
     MyEnum obj;
     obj = (MyEnum)5;
     Console.WriteLine(obj.ToString());
     Console.ReadLine();
   }
}

Did you noticed something? Our Enum only had 0,1 and 2 as valid values. I went on and assigned 5 to it. Now try compiling this code. Aha! no compilation errors. Now try running this. Everything goes well and 5 gets printed on console. Did you expected this?
I never expected this. Did Microsoft forget about type safety and type checking issues while copying from Java Enums? I think Java enums works fine.
If you ever worked with Bit Flags you will some how realize that all of this is due to them. Bit flags can actually take up values which are a combination of values that are defined in Bit Flag Enum. Here is an example:
[Flags]
internal enum Actions
{
  None = 0,
  Read = 0X0001,
  Write = 0X0002,
  ReadWrite = Actions.Read Actions.Write
  …
}

There are number of threads going on in forums related to this. Just keep this in mind before using Enums.

Tags: ,

Leave a Reply