none
Structures Containing the Reference type RRS feed

  • Question

  •     struct MyStruct
        {
            public string myString;
    
            static void Main(string[] args)
            {
                MyStruct myVariable = new MyStruct();
                myVariable.myString = "Hello"; //This Line
                Console.ReadLine();
            }
        }

    Where does myString and myVariable.myString gets Stored? Heap or Stack ? 

    • Edited by slalithp Sunday, February 17, 2019 6:52 AM
    Sunday, February 17, 2019 6:51 AM

Answers

  • "myVariable" gets stored in the Stack. Within its frame in the stack, there will be some space (10 bytes iirc) allocated for a reference that points to myString. The actual string allocated to myString will be in the Heap. The reference in the Stack points to the location in the Heap.

    Or, at least, this would be the general behavior for a reference type. The String type is a special case and may be treated differently. In particular, the "Hello" string is likely to be present in the code segment, and since strings in .Net are immutable it is posible that the reference in the Stack may be pointing directly there, rather than having the value copied to the Heap.

    • Marked as answer by slalithp Friday, February 22, 2019 3:22 AM
    Sunday, February 17, 2019 1:16 PM
    Moderator

All replies

  • "myVariable" gets stored in the Stack. Within its frame in the stack, there will be some space (10 bytes iirc) allocated for a reference that points to myString. The actual string allocated to myString will be in the Heap. The reference in the Stack points to the location in the Heap.

    Or, at least, this would be the general behavior for a reference type. The String type is a special case and may be treated differently. In particular, the "Hello" string is likely to be present in the code segment, and since strings in .Net are immutable it is posible that the reference in the Stack may be pointing directly there, rather than having the value copied to the Heap.

    • Marked as answer by slalithp Friday, February 22, 2019 3:22 AM
    Sunday, February 17, 2019 1:16 PM
    Moderator
  • so myVariable.myString stays in stack and references to "Hello" in heap, Thank you :) 
    Friday, February 22, 2019 3:23 AM