Tuesday, September 23, 2008

Beware the enum-compilation!

I was recently made aware of a real eye-opener when it comes to how enums are compiled by the c# compiler.

When you compile a c# project, each enum is internally replaced with the corresponding value of the enum. What that mean is that in the IL code the reference to the enum is replaced by the integer value in the enum.

This could give you a problem if you redefine an enum that is used across multiple dlls. Say you have an enum with two values, and you decide to switch their place in the enum definition. If you only compile the dll with the enum definition, the other dll will work the opposite of what is fairly natural to expect!

The enum tip of the day is thus:

  • Always specify the value of the enum in the defintion rather than using the default order.

  • Never replace a value with another, always add new values to a number higher than the current top

  • Always follow the points above. Would you like try to debug a patch creating that problem?

1 comment:

Anonymous said...

Interesting errors can occur when you rebuild one or some assemblies using the new enum values, without considering what will happen when your objects go from assembly to assembly.

Gives you a good reason to read up on versioning of assemblies. :)