Can anyone explain diagrammatically how enum is stored in memory?

前端 未结 3 868
一生所求
一生所求 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:09

    enums are not allocated in memory - they exist only on compilation stage. They only exist to tell compiler what value is Tuesday in ur example. When code runs - there is no enums there anymore.

    It does same thing as below

    #define Monday 0;
    #define Tuesday 1;
    .
    .
    .
    .
    #define Sunday 6;
    

    But we prefer enums than define because easier to support and read the code with enums then with #defines.

    u can get clarity of enum size by this Stackoverflow answer

    0 讨论(0)
  • 2021-01-23 04:16

    Enums are stored constants.
    Once a list of values is created for a enumeration those values are stored as literals against their display name(access name given at the time of declaration of enum). Pier's answer is appropriate for the storage. Check ILDASM tool to checkout enum literals in IL code.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题