Search code examples
c#.netstringclr

Is it possible to read all strings in the intern pool?


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:

  • It possible to read all the strings that are currently in the intern pool?
  • Is there a way to get a reference count to each interned string?
  • Would it be possible to read the intern pool from a separate process space?
  • If none of these are possible, what's the reasoning for not allowing these use cases?

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.


Solution

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