HandleThatError
HandleThatError

Reputation: 640

What happens to memory behind the scenes when creating new objects inside of C# for loops?

I'm trying to understand when memory gets allocated and when the garbage collector collects garbage. Let's say that I have some code like this:

foreach (FileInfo f in File){
    foreach (DataAtrribute d in f){
        string name = d.name;
    }
}

Let's say there are thousands of FileInfo objects held in an array inside of a File object. Let's say that inside each FileInfo object is a collection containing multiple DataAttribute objects. Will this code result in many blocks of memory being reserved over and over for "string name" since instead of having a single static string named name I'm doing 'string name = d.name" over and over? Or does the garbage collector work fast enough to avoid this and to keep free memory CONTIGUOUS?

Thanks.

Upvotes: 0

Views: 269

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79441

string name = d.name; defines a reference to a string on the stack, and assigns that references to point to an existing string object in memory, so there isn't any heap allocation.

Upvotes: 2

Related Questions