The Dispose Pattern : IDisposable « Class Interface « C# / C Sharp






The Dispose Pattern

 
using System;


public class MyClass {
    private string name;
    public MyClass(string name) { this.name = name; }
    override public string ToString() { return name; }
    ~MyClass() { Console.WriteLine("~MyClass()"); }
    public void Dispose() {
        Console.WriteLine("Dispose()");
    }
}

public class GarbageDisposalApp {
    public static void Main(string[] args) {
        DoSomething();
        Console.WriteLine("end of Main");
    }
    public static void DoSomething() {
        MyClass t = new MyClass("Foo");
        Console.WriteLine(t);
        t.Dispose();
        t = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

 








Related examples in the same category

1.The IDisposable Interface
2.Derived Disposable Classes
3.Protecting Against Double Disposal
4.The constructor initializes the internal object. The Dispose method closes the file resource. The destructor delegates to the Dispose method.
5.using statement with IDisposable interface