I need to decide if I will use enum
s in a big array I need in my project. To do that I have to know what is size of an enum
variable.
enum Player
{
First,
Second,
Third,
Fourth
};
private Player _owner;
How much memory will _owner
take?
I haven't found proper information about this in C#, that's why this C++ and Java topic does not apply: How much memory do Enums take?
On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.
No. These are constants and doesn't take any memory nor they have address.
Enum does not, in itself take any space, but in implementations that adhere to standard C making the enumerated variable an int, they do cost you one byte, if you otherwise would have used a char.
Enum
values are converted to values of the underlying type at compile time. Therefore, a variable of an enumeration type itself based on int
type (which is the default) doesn't use any more memory than any other int
variable in your code.
An Enum
underlying structure can be any of the following:
byte
sbyte
short
ushort
int
uint
long
ulong
Since your Player
enumeration type does not specify the underlying time, the compiler will see it as an int
-based Enum
. If memory is a concern, you may want to consider declaring it as derived from byte
instead:
enum Player : byte
{
First,
Second,
Third,
Fourth
};
Be careful though: a newly declared Enum
variable will have the same value as it's underlying type's default value, which will always be zero. In an enum with unspecified literal values, the first item in the list is assumed as the default value. In your case, that would be First
:
private Player _owner; // this value will initially equals Player.First
You may want to insert an additional Player
literal labelled None
, Empty
or Undefined
to represent a Player
variable default value:
enum Player : byte
{
Undefined = 0;
First,
Second,
Third,
Fourth
};
private Player _owner; // this value will initially equals Player.Undefined
Of course, if you are okay having First
as the default value, you may leave it as is. Be aware though that not having a dedicated default Enum
value is often considered a bad coding practice.
As an alternative, since any Enum
are structure-based, you may also declare your _owner
variable as Player?
so that it will instead be null
by default:
private Player? _owner; // this value will initially equals null
To sum it up, simply remember that Enum
literals simply acts as constants for their underlying type. Their purpose is to make code easier to read and to enforce a limited set of possible values at compile time.
For more information, look at the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With