Tuesday 22 July 2014

Enums in C#; Doing More Than You Thought!

I have been developing for a while now and use Enums on a daily basis (nearly) and was quite happy in my understanding an Enum definition had a set number of values and of those values they could be cast to the related integer value (or another under-lying type) and back again.

And then I saw the following piece of code (condensed down for example):

System.Net.HttpStatusCode value = (System.Net.HttpStatusCode)429;
var result = (429 == (int)value);

There is no corresponding value in System.Net.HttpStatusCode which relates to 429 and the value of result variable was true when when the enum value was cast to an int!

So why is this possible? Enter the C# specification!

Quick side note; no need to search the internet for the C# language specification if you have Visual Studio 2013 installed locally you already have it. It can be found:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Specifications\1033

A quick browse to section 1.10 Enums answered, high level, why it is possible straight away.

“The set of values that an enum type can take on is not limited by its enum members.”

The rest of the section is quite interesting as well with regards to the underlying type of the enum type. On further reading of chapter 14 – Enums there are a lot of bits which as a developer you take for granted and use without really thinking it about. It’s actually quite interesting.

Makes me wonder what else I’m missing out on, maybe I should read more of the specification? Maybe the whole specification?