The constructor initializes the internal object. The Dispose method closes the file resource. The destructor delegates to the Dispose method. : IDisposable « Class Interface « C# / C Sharp






The constructor initializes the internal object. The Dispose method closes the file resource. The destructor delegates to the Dispose method.

 

using System;
using System.IO;


public class WriteToFile : IDisposable {

    public WriteToFile(string _file, string _text) {
        file = new StreamWriter(_file, true);
        text = _text;
    }

    public void WriteText() {
        file.WriteLine(text);
    }

    public void Dispose() {
        file.Close();
    }

    ~WriteToFile() {
        Dispose();
    }

    private StreamWriter file;
    private string text;
}

public class Writer {
    public static void Main() {
        WriteToFile sample = new WriteToFile("sample.txt", "My text file");
        sample.WriteText();
        sample.Dispose();
    }
}

 








Related examples in the same category

1.The IDisposable Interface
2.Derived Disposable Classes
3.Protecting Against Double Disposal
4.using statement with IDisposable interface
5.The Dispose Pattern