Are strings garbage collected?

Are strings and static fields garbage collected?

  • 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.

  • Answer:

    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.

Royi Namir at Stack Overflow Visit the source

Was this solution helpful to you?

Other 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.

Etienne de Martel

No, the garbage collector will not collection the static fields. in general the garbage collection will not collection you classes as long as an instance of your class exists and is pointed to it will stay.

Jalal Aldeen Saa'd

Any static field that references an object will prevent that object from being collected, since static fields are associated with the Type object for a class. Those in turn are associated with an AppDomain, and thus will serve as GC roots. For strings, it is dependent on whether or not it has been interned. If it has, then the intern pool for the current AppDomain will reference it and thus prevent collection. If not, then a string will behave like any other class object, and be eligible for collection when it is no longer accessible via a chain of references from a GC root. Note that in both cases, if the AppDomain is unloaded, the objects will become eligible for collection.

dlev

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.