What happens under the hood when you impose an enum on an int in C #?

I am looking to implement an emulator in C #.

One of the things I've considered is creating an enumeration of all opcodes associated with their byte value. However, I wonder, it might not be a good idea, given how often I need to access this byte value in order to do things like use it as an index in a lookup table, etc. Etc.

When you enter an enumeration into an int, what happens? How expensive is the operation? Would it be more reasonable to simply define my opcodes as const bytes by their name?

+4
source share
2 answers

This is very cheap - it is effectively non-op, indeed, if enum has the base int type to start with (which is the default). For example, here is an example program:

 using System; enum Foo { A, B, C }; class Test { static void Main() { Foo x = Foo.B; int y = (int) x; } } 

And the generated code for Main (not optimized):

 .method private hidebysig static void Main() cil managed { .entrypoint // Code size 6 (0x6) .maxstack 1 .locals init (valuetype Foo V_0, int32 V_1) IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ret } // end of method Test::Main 

The drop effect is used for the compiler - the data in memory is already in the corresponding state, so you just need to copy the value as if it were copying int to int .

If the base enumeration type is not int , then converting the enum to int has the same effect as casting the base type to int . For example, if the base type is long , you will get something like conv.i4 in the same way that you usually do long before int .

+9
source

It depends a little on whether the enumeration system itself will be int ; p

If so, nothing happens - the enumerations are fully represented in their int / long in any form, until you set them. Casting from MyEnum : int <===> int is non-op. Most of the differences that you are familiar with in terms of resolving method overloads, etc., exist solely for the compiler; at the IL level there is no difference.

+5
source

All Articles