Does WeakReference work with String?

In .NET 3.5, does WeakReference work with String or should I wrap it in a small "class" for it to work with it?

+2


source to share


3 answers


System.String

( string

in C #) is a reference type, so there is no reason it shouldn't work well with WeakReference

. Ignore the fact that this is a kind of special reference type (immutable, to begin with) - the CLR sees it as a reference type.



Speaking of which, fooobar.com/questions/1277790 / ... gives a good idea that string references can be "interned" in many situations, and therefore "expected" garbage collection behavior is not observed.

+2


source


This will certainly work with WeakReference without any problem since System.String is a simple reference type. It would be interesting to see your use case for using WeakReference as it doesn't seem to follow "normal" use of WeakReference.

From MSDN Guide :

Use long weak references only when necessary, as the state of an object is unpredictable after completion.



Avoid using weak references to small objects, because the pointer itself can be large or large.

Avoid using weak links as an automatic solution to memory management problems. Instead, create an efficient caching policy to handle your application objects.

+1


source


It usually doesn't make much sense to use a weak reference to point to a deeply immutable object, especially one that doesn't reference any other objects. If the data is useful, you should have a strong link. If this is not helpful, you should not include any links. The use of WeakReference is really realistic in cases where the usefulness of a loosely coupled object depends on having a strong reference; the most common case is that a weak link is used to put information into an object that will be read using a strong link. If no one is going to read the information placed in the object, there is no reason for the writer to worry anymore.

0


source







All Articles