Does the following function code / t 20> invalidate?
Could this cause a flaw in the GC?
class Program { static Dictionary<string , DisposableClass> Disposables { get { if (disposables == null) disposables = new Dictionary<string , DisposableClass>(); return disposables; } } static Dictionary<string , DisposableClass> disposables; static void Main(string[] args) { DisposableClass disposable; using (disposable = new DisposableClass()) {
Output: SuperDisposable
My understanding of the using(...) function is to force the disposition of DisposableClass immediately. However, inside the code block, we add the class to the dictionary collection. I understand that a class is essentially a reference type. So my experiment was to see what would happen to a one-time item added to the collection in this way.
In this case, the DisposableClass is still quite lively. Classes are a reference type - therefore, my assumption was then that the collection not only refers to this type, but really contains the class as a value. But that also made no sense.
So what is going on?
EDIT: A modified code with exit to prove that the object is not dead, which may be suggested by some answers.
2nd EDIT: what's connected with this as I went through another code:
public void Dispose( ) { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool dispose) { if (!isDisposed) { if (dispose) {
Code execution (had a breakpoint with private void Dispose(bool dispose) ), where false is passed to the method, it becomes necessary that the resources are properly disposed of here. Despite this, the class is still alive, but you are definitely setting yourself up for exceptions. The answers made me more curious ...
source share