Tuesday, December 4, 2007

Crazy Enums

Few days back I got a great opportunity to talk with a senior thoughtworker, Chris. He told me few things related to Agile and NUnit. Apart from this there was 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

Now create another class where we will use this Enum,

class Program
static void Main(string[] args)
MyEnum obj;
obj = (MyEnum)5;

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 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:

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.
I am exited about playing EA Game's CRYSIS. I have the DVD and will be installing the game tomorrow. Actually I need to clean up my system a bit before I get on with the game. CRYSIS CD says, "Game needs 20 Gb of free hard drive space."

Currently listening to: Black or White - MJ
~nJoY CoDiNg~