In .NET 3.5, Does WeakReference work with String or shall I wrap it in a small "class" to make it work with it?
This will definitely work with WeakReference without any problems as System.String is a simple reference type. It would be interesting to see your use case for using a WeakReference as it doesn't seem to fit the "normal" uses of WeakReference.
From the MSDN Guidelines:
Use long weak references only when necessary as the state of the object is unpredictable after finalization.
Avoid using weak references to small objects because the pointer itself may be as large or larger.
Avoid using weak references as an automatic solution to memory management problems. Instead, develop an effective caching policy for handling your application's objects.
System.String
(string
in C#) is a reference type, so there is no reason it should not work perfecctly well with WeakReference
. Ignore the fact that it is in some ways a special reference type (immutable, for a start) - the CLR sees it as a reference type.
Saying this, this other StackOverflow thread makes a good point that string references can be 'interned' in many situations, and therefore the "expected" behaviour with regards to garbage collection is not observed.