Chengting
Chengting

Reputation: 355

Array member reference and garbage collection

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?

Upvotes: 2

Views: 210

Answers (2)

Shinva
Shinva

Reputation: 2304

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

Upvotes: 2

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

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.

Upvotes: 3

Related Questions