The WeakReference
class does exactly what you want, using the IsAlive
property to check for state before using it.
You can get a "strong" reference to it again via the Target
property, which will affect the reference count and stop it from being eligible for collection.
Also note that Dispose
doesn't directly relate to garbage collection, so disposing an item (depending on the Dispose
implementation) might make it unusable anyway - but again, that is nothing to do with GC. On a general practice note, as mentioned by @HansPassant, calling Dispose
on an item (or generally anything claiming to dispose) and then attempting to use it again afterwards is a code smell (or just plain wrong as other developers will expect Dispose
to be a last-call method marking the object as unusable from then on).
The WeakReference
class will not be responsible for re-creating collected objects, but in conjunction with IsAlive
you can handle that logic yourself.
Also, to the point in the comments, the GC doesn't do anything clever with WeakReference
in terms of deciding when to collect it in terms of trying to leave WeakReference
items until last; it will collect the underlying object as it would others during a run if it is eligible - no special handling and definitely no "cache" behaviour.