locked
Can Struct stored in heap?! RRS feed

  • Question

  • Hello my friends,

    Can struct stored in heap? i think struct just can stored in stack memory.

    Wednesday, July 22, 2015 6:41 PM

Answers

  • "What's meaning about "inline" ?"

    Frankly I don't know. Given the rest of the text I would assume that's shoddy book speak for structs used as fields.

    "So the following struct stored in heap?"

    That will be stored on heap or stack depending on how it is used.

    Let's put it another way:

    • Structs are not stored anywhere, local variables and fields are.
    • Local variables are stored on stack no matter what type (class or struct) they have. The difference is that a local variable of struct type stores the struct instance and a local variable of reference types stores a reference to the class instance that's stored on the heap.
    • Fields are stored in the object they belong too. If the object is of reference type then it's stored on the heap and so are its fields. If the object is of struct type then it may be stored on stack (as a local variable) or on the heap (as a field of another object).
    • Marked as answer by Arash_89 Wednesday, July 22, 2015 9:02 PM
    Wednesday, July 22, 2015 8:43 PM
    Moderator

All replies

  • That's exactly what the text is telling you, that structs are stored in heap when they're fields of reference types. Structs are also stored in the heap when they're boxed. What makes you think that they can only be stored in stack memory?

    Wednesday, July 22, 2015 8:07 PM
    Moderator
  • Thanks,What's meaning about "inline" ?
    Wednesday, July 22, 2015 8:14 PM
  • So the following struct stored in heap?

        struct Dimensions
        {
            public double length;
            public double width;
            public string NEW;
        }

    Wednesday, July 22, 2015 8:26 PM
  • "What's meaning about "inline" ?"

    Frankly I don't know. Given the rest of the text I would assume that's shoddy book speak for structs used as fields.

    "So the following struct stored in heap?"

    That will be stored on heap or stack depending on how it is used.

    Let's put it another way:

    • Structs are not stored anywhere, local variables and fields are.
    • Local variables are stored on stack no matter what type (class or struct) they have. The difference is that a local variable of struct type stores the struct instance and a local variable of reference types stores a reference to the class instance that's stored on the heap.
    • Fields are stored in the object they belong too. If the object is of reference type then it's stored on the heap and so are its fields. If the object is of struct type then it may be stored on stack (as a local variable) or on the heap (as a field of another object).
    • Marked as answer by Arash_89 Wednesday, July 22, 2015 9:02 PM
    Wednesday, July 22, 2015 8:43 PM
    Moderator
  • Wednesday, July 22, 2015 8:58 PM