As we saw in previous post, we can use using statement to automatically dispose of objects. To use using directive our class needs to implement IDisposable interface. To correctly implement IDisposable interface we should stick to some guidelines. Following example will show you the correct way to implement it.
Example of Implementing IDisposable interface to a class
We will start by creating FileRead class whose job is to create file and write line to it. FileRead class will implement IDispose interface and two Dispose methods. General rule is that you should create two Dispose methods:
- public void method with no parameters
- protected void method with a boolean input parameter
Job of public Dispose method is to call second Dispose method where objects are really disposed of, and second job is to notify Garbage collector that this instance of class is cleaned up and that there is no need to check-up upon it during garbage collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
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; } } } } |
More examples of IDisposable coming up soon.
Leave a Reply