Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings and Garbage Collection

Tags:

I have heard conflicting stories on this topic and am looking for a little bit of clarity.

How would one dispose of a string object immediately, or at the very least clear traces of it?

like image 709
Kyle Rosendo Avatar asked Mar 11 '10 06:03

Kyle Rosendo


2 Answers

That depends. Literal strings are interned per default, so even if you application no longer references it it will not be collected, as it is referenced by the internal interning structure. Other strings are just like any other managed object. As soon as they are no longer reference by your application they are eligible for garbage collection.

More about interning here in this question: Where do Java and .NET string literals reside?

like image 165
Brian Rasmussen Avatar answered Nov 04 '22 00:11

Brian Rasmussen


If you need to protect a string and be able to dispose it when you want, use System.Security.SecureString class.

Protect sensitive data with .NET 2.0's SecureString class

like image 29
CG. Avatar answered Nov 04 '22 01:11

CG.