Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are strings and static fields garbage collected?

Tags:

c#

.net

clr

When do strings and static fields get reclaimed by the garbage collector?

I'm asking this because I know statics in ASP.NET are always live.

like image 784
Royi Namir Avatar asked Jul 29 '11 20:07

Royi Namir


2 Answers

The garbage collector only collects objects that are not accessible. An object referenced by a static field is accessible as soon as its class is loaded, so it will obviously not get collected (unless of course the field is set to refer to something else, causing the original object to become potentially eligible for collection).

As for strings, it depends. Literal strings are interned and therefore always accessible. Otherwise, same rules apply as for any object.

like image 80
Etienne de Martel Avatar answered Oct 31 '22 03:10

Etienne de Martel


Strings are objects and will be collected when un-referenced.

static fields usually keep a permanent reference to an object and thus keep those objects from being collected. But as long as you still need those objects that's quite alright.

like image 37
Henk Holterman Avatar answered Oct 31 '22 03:10

Henk Holterman