I’m looking to implement an emulator in C#.
One of the things I considered was creating an enum of all the opcodes associated with their byte value. However, I wonder if this might not be a good idea considering how often I’m going to need to access that byte value to do things like use it as the index in a lookup table, etc, etc.
When you cast an enum to an int, what happens? How expensive of an operation is this? Would it be more prudent to simply define my opcodes as const bytes by their name?
It’s very cheap – it’s effectively a no-op, really, assuming the enum has an underlying type of
intto start with (which is the default). For example, here’s a sample program:And the generated code for
Main(not optimized):Effectively the cast is for the sake of the compiler – the data in memory is already in an appropriate state, so it just needs to copy the value just like it would copying an
intto anint.If the underlying type of the enum isn’t an
int, then casting the enum tointhas the same effect as casting the underlying type toint. For example, if the underlying type islong, you’ll end up with something likeconv.i4in the same way that you would castinglongtointnormally.