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