Interesting behaviours with enum in .NET

This is completely plausible and the check is avoided first for performance reasons. Just imagine the CLR having to enumerate all the valid values and check whether yours falls in it, this no longer becomes a simple cast. The other reason is versioning. That is why you have Enum.IsDefined(…). Some developers now rely on this feature when dealing with an enum defining flags. When they want to set all flags they simply cast int.MaxValue to Enum

Bernado Nguyen-Hoan's Blog - Coding Stories from an IT Mercenary

When defining an enum type, we can assign an int value to each of the enum members. Below is an example.

Now there are two behaviours that you may not be aware of. Firstly, given the above definition, you can actually assign any int value to a variable of type Status. Let say I have a class as below.

The following code will then happily compile and execute:

OK, who on earth would be doing something like that? Probably not many, but this leads on to the second behaviour: by default, the value of the enum will be 0, even if 0 is not one of the defined enum members.

So with the code below, the value of record.Status will be 0, which does not match any of the defined status values:

This behaviour could have an impact on your code if not handled properly. This is because when defining an enum…

View original post 95 more words

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: