There is little you can do with strings supplied as string constants: they are interned, so they would not be garbage collected until your program exits.
Note that using SecureString
would not help in this situation, because if you copy the content of a string literal into an instance of SecureString
, your string literal would remain in the image of your program.
On the other hand, when the source of your string is not a literal or a constant, you would be able to prevent the content of your string from remaining in memory longer than you need it:
OracleConnection conn;
using (var pwd = new SecureString()) {
pwd.Append(...); // Append characters of the password to the string
... // Append more characters...
conn = new OracleConnection(pwd);
}
// At this point pwd is erased from memory