It's well known that in some certain cases when using strings in C#, the CLR does string interning as an optimization.
So my questions are:
I could see this being somewhat useful when monitoring memory usage in certain cases. It may also be useful when working with sensitive information (although I would think SecureString
would be more preferable in many scenarios).
As far as I can tell, the only public methods related to string interning are String.Intern(string)
and String.IsInterned(string)
I'm asking out of curiosity, not trying to solve a real problem. I realize that doing any logic based off of the string intern pool would be a bad idea.
Looking up the interned strings via code has no use case so it's feature was not added in to the language.
However looking up the strings in memory while debugging a program is a very common use case, and there are tools to do that.
You will need to use the tool WinDbg.exe
that comes with the Windows SDK. After launching it and attaching it to your program you do the command
.loadby sos clr
and that will load in the extensions for debugging .NET apps. Once you have done that you can do the command
!DumpHeap -strings
and you can see all string objects in the heap.
As for telling if the object in that list that you are looking at is interned or not, I am not entirely sure how. Hopefully if you ask a new question about WinDbg and how to tell if a string is interned or not someone may be able to answer.