yer doin it wrong.

How to not do things.

Wednesday, June 14, 2006

C# Enums and Compilers

Here's an interesting one.

Let's say you have an enum defined in one assembly, call it 'E'.
Now, let's say that you have another assembly (call it 'A') that has a reference to E in the .csproj file.
Finally, let's say that in A, you only use the values in E with casts to ints. Something like this

public static void Main(string[] args)
{
int x = (int) E.E1;
}

The compiler will (can?) do a nasty little number on you and remove the reference to the assembly and substitute the int value. So if you take a look at the IL or do reflection on assembly A, there will be no sign of E. And if you go look at the disassembled code, there will be an integer constant in the place of your enum.

Here is one last little bit... If you reference assembly 'A' in a Web Project (those awful, awful things in VS2005,) then you get a reference to 'E'. If you use the enums in E in one of your WebApp classes, then everything is fine and dandy. Until you try to build outside of the IDE, (using MSBuild, for instance.) It cannot figure out that to use A, you should already have E and therefore you shouldn't need an explicit reference to it. The IDE figures this out for you.

The solution? Use one of those .refresh files to force the Web Project to include the E assembly. This means that you must explicitly add the reference to the Web Project and cannot rely on the fact that it seems to have pulled in the reference when you added A.

Update
Looks like the MSBuild guys were able to reproduce this... Waiting to see if there might be an emminent fix.

0 Comments:

Post a Comment

<< Home