views:

155

answers:

2

In .NET 3.5, Does WeakReference work with String or shall I wrap it in a small "class" to make it work with it?

+1  A: 

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.

Ray Booysen
My case is I've got so many strings, normally they are stored in DB and I only want to release them when I'm out of memory. Actually a better caching would be better, but I couldn't find any good way to release cache when memory is low.
dr. evil
+2  A: 

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.

Noldorin
That was my first thought, but is that true? See also this question: http://stackoverflow.com/questions/208387/weakreference-bug
Razzie
@Razzie: That's just an implication of how the GC happens to work with strings.
Noldorin