using System;
using System.IO;
namespace SimpleIDisposableImplementation
{
class Program
{
static void Main(string[] args)
{
// Application starts here and calls
// FileRead class that implements IDisposable interface.
// We supply FileRead constructor with location of our txt file
using (FileRead read = new FileRead(@"d:\test.txt"))
{
// FileRead.Dispose method is called after exiting using statement
}
}
}
public class FileRead : IDisposable
{
private FileInfo _fileInfoInstance;
private StreamWriter _streamWriter;
private bool disposed;
public FileRead(string filePath)
{
_fileInfoInstance = new FileInfo(filePath);
CreateFileAndWriteToIt();
}
private void CreateFileAndWriteToIt()
{
_streamWriter = _fileInfoInstance.CreateText();
//_fileInfoInstance.Exists property tells us
// if file exists by returning boolean value
if (_fileInfoInstance.Exists)
{
_streamWriter.WriteLine("Hello World");
}
}
public void Dispose()
{
// We call our protected virtual Dispose method
// and do real cleanup there
Dispose(true);
// Garbage collector is notified
// that we have cleaned this instance
// is cleaned and needs not to be finalized
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool indDisposing)
{
//First we check if object is Disposed of
if (disposed == true)
return;
if (indDisposing == true)
{
// Then we check for state of object
// No need to dispose of if
// instance is null
if (_streamWriter != null)
{
// We dispose of object
_streamWriter.Dispose();
// And to be shure we
// set it to null
_streamWriter = null;
}
// Lastly we set disposed field to true
// to set a flag that object is disposed of
disposed = true;
}
}
}
}