Derived Disposable Classes : IDisposable « Class Interface « C# / C Sharp






Derived Disposable Classes

 
using System;
public class MyClass : IDisposable
{
    protected string name;
    public MyClass(string name) { this.name = name; }
    override public string ToString() { return name; }
    ~MyClass() { Dispose(); Console.WriteLine("~MyClass()"); }
    public void Dispose() 
    { 
        Console.WriteLine("MyClass.Dispose()"); 
        GC.SuppressFinalize(this);
    }
}
public class SonOfMyClass : MyClass, IDisposable
{
    public SonOfMyClass(string name) : base(name) { }
    override public string ToString() { 
       return name; 
    }
    ~SonOfMyClass() { 
       Dispose(); 
       Console.WriteLine("~SonOfMyClass()"); 
    }
    new public void Dispose()
    { 
        base.Dispose();
        GC.SuppressFinalize(this);
    }
}
   
class DerivedDisposeApp
{
    static void Main(string[] args)
    {
        DoSomething();
    }
    static void DoSomething()
    {
        SonOfMyClass s = new SonOfMyClass("Bar");
        Console.WriteLine(s);
        s.Dispose();
    }
}

 








Related examples in the same category

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