Can anyone explain diagrammatically how enum is stored in memory?

前端 未结 3 902
一生所求
一生所求 2021-01-23 03:47

How Enumeration datatype is stored in memory?Is enum really stored in memory in stack?How each value of enum is accessed?

i have gone through many blogs stating that

3条回答
  •  难免孤独
    2021-01-23 04:18

    An enumeration is an interpretation of a numeric datatype inferred by the compiler (usually an integer, but you can change it).

    The compiler introduces a new type for each enumeration you define. The newly defined type is particular, because you cannot inherit from, and contains operators that you can use to cast it from and an integral type.

    From the memory perspective, the enumeration is stored in a value of integral type capable of containing all the values you have declared.

    The CLR provides this as a base service, therefore languages like c# have this behavior. This might not be the rule for every. Net supported language.

    As enum types are handled as integral types, they are stored in the stack and registers as their respective data types: a standard enum is usually implemented as an int32; this means that the compiler will handle your enum as a synonym of int32 (for the sake of simplicity, I left out several details). Hence your enum is at the end an int32.

    If you want to control how an enum is implemented, you can declare it this way:

    enum MyEnum: byte{}
    

    In the example above, MyEnum is a byte, therefore the compiler will handle it as a byte.

提交回复
热议问题