2

If a member of an array is kept being referenced, the whole array will not be garbage collected?

for example, a method:

    void ParseUtility(string strInput, out string header)
    {
        header = "";

        string[] parsed = strInput.Split(',');
        if ((parsed != null) && (parsed.Length > 0))
        {
            header = parsed[0];
        }
        return;
    }

when returning from this method, the whole string array 'parsed' will be kept as long as 'header' is being used?

Chengting
  • 345
  • 2
  • 4
  • 11

2 Answers2

3

That is not the case. string is a class, so any string instance has an independent existence - each element of the array simply refers to a string, and header = parsed[0] retains a reference to the string, not to the array. Whether the array may be GC'ed depends solely on whether the array itself is reachable.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
  • which means, .net framework always maintains objects by the smallest reference units? - for List, HashSet etc, the framework gets its independent collections of List or HashSet's child members? – Chengting Nov 05 '15 at 06:31
  • Yes; even if you have a tiny class whose only member is a single `bool`, instances of that class are individually tracked and GC'ed. – Aasmund Eldhuset Nov 05 '15 at 15:51
2

Should not. parsed has a reference to parsed[0] not the other way around.

Shinva
  • 1,899
  • 18
  • 25