How is memory allocated when you create a property of class?

我的梦境 提交于 2019-12-24 09:48:06

问题


I have the following class:

public class A
{
    public List<string> AList { get; set; }
}

Then I create object of a class:

A objectA = new A();
objectA.AList = new List<string>() { "1", "2", "3" };

My question is how memory will be allocated in a heap? I mean will be objectA.AList allocated inside of objectA (image1) or as a separate object in a heap(image2)

Image1:

Image2:


回答1:


The correct answer is : Image 3.

I'm not going to draw this but your example leads to 5 objects on the Heap.

Objects (instances) don't have names but they are referred to by the following references:

  1. objectA
  2. objectA.AList
  3. objectA.AList[0]
  4. objectA.AList[1]
  5. objectA.AList[2]

Each string is also an object on its own.

The objectA instance only contains a reference to the List, and the List holds an array of references to strings. 3 are used, more might be allocated and still be null.

None of these objects lives 'inside' another.



来源:https://stackoverflow.com/questions/37293387/how-is-memory-allocated-when-you-create-a-property-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!