C# - 2 - Making MVC models disposable.

[C# 2.0]

Assuming you have a model class (such as might be used in an MVC pattern) and you want to ensure it doesn't leak. You make it disposable.

First, add the IDisposable interface to the class definition:

Add a flag …

Then add the following code …

You will need to determine what code is required in the tidy up section of the dispose method. Typically it's where you dispose of all the class's disposable components (DataSets, DataTables, Bitmaps, etc that are class members). Note that destructors (finalisers) are 'expensive', but if the dispose method is called the destructor wont be. The purpose of the destructor here is to catch and flag up when the class is finished without being disposed.

Finally, add a call to CheckDisposed() as the first line of every public method. This will catch and flag up when attempts have been made to use the class after it's been disposed of.

Your class is now disposable. Remember that your program will need to call this class's dispose method before it is destroyed … you may want to add a reference to Dispose() in it's interface (in this example that is ImodLogin).

.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License