When declaring an enum, should you force the type to byte for under 256 entities?

No. Don't prematurely optimize unless you've proved with a profiler that it's actually a problem.


Relating to best practice:

When you don't have a particular reason for making the enum a type byte, you should leave it as the default.

Any time you use an enum in a switch statement you should have a "default" clause for an invalid enum value. So it doesn't matter if you are checking for 256-NumRealEnumValues or 2^32-NumRealEnumValues. Both will have a default clause that handles all invalid cases.

One reason for explicitly setting the type of the enum, is if you want your enum to correspond to another type in your program and you need to explicitly cast between them.

Changing the type to the smallest fit will not help you with versioning problems either. Unless you have exactly the max size of the enum filled out. By versioning problems I mean when you have a compiled dll using the enum, then you add a new enum value, some code may execute that was not meant to go in the "default" clause of a switch statement.

Relating to efficiency:

No there is no benefit in terms of efficiency to make it a byte.

int is more efficient to use because the cpu on x86 has 32-bit registers. Copying into a register is done 32-bits at a time.

When you use a smaller type, you have to zero out part of the register and copy into the rest of the register's lower order bits.

Tags:

C#

Types

Enums