Idisposable Interface. RRS feed

  • Question

  • User-256025523 posted

    Hi Friends,

                  As per my understanding, we need not to care of disposing managed code. But still if i want to explicitly achieve it , how can i do it in C# buy using Idisposable as Good practice? For example i have class i.e. Maths given below. Please provide code snippet to dispose this class. 

    public Class Maths


     public int add (int a, int b)

       return a+b;


    Sunday, January 10, 2016 11:58 AM


  • User1124521738 posted

    you don't have to care at the low level, but you should still care at a high level and not go creating lots of objects that have IDisposable and not leverage where ever possible so as to keep your code from developing memory leaks.

    see also http://www.codeproject.com/Articles/413887/Understanding-and-Implementing-IDisposable-Interfa and http://www.codeproject.com/Articles/15360/Implementing-IDisposable-and-the-Dispose-Pattern-P

    IDisposable is typically used when there are expensive operations so as to allow for a specific scope for the lifecycle and to provide a cleanup opportunity.

    your class doesn't really have anything expensive, but you might want it to only have a particular scope:

    	public class Maths : IDisposable {
    		public int add(int a, int b) {
    			return a + b;
    		public void Dispose() {
    			// do cleanup here

    and to use it with a scope

    			using (var m = new Maths()) {
    				int j = m.add(10, 12);

    the most common usage contexts are data connectivity such as SqlConnection, SqlCommand, SqlDataAdapter, etc. As well as FileStream, MemoryStream, LINQ-to-SQL db connection classes: DataContext, etc.

    if you are working with LINQ in an MVC controller, you may want it to live across the whole class rather than just the single action because you plan to leverage extended sql properties from the list or single entity returning, and otherwise you'd get a "cannot execure after closed" error.  You can chain the LINQ dispose with the controller's close

    public class AdminController : Controller {
    	protected NorthwindDataContext db = new NorthwindDataContext();
    	// actions etc go here

            public ActionResult ViewSupplier(int id) {
                return View(db.Suppliers.Where(x => x.SupplierID == id).FirstOrDefault());
            } //======================= protected override void Dispose(bool disposing) { if (db != null) { db.Dispose(); } base.Dispose(disposing); } }

    It also shows up in a number of MVC razor html helpers so that as part of dispose emits the close tag for the html being output (see http://www.codeguru.com/columns/dotnet/writing-your-own-mvc-helpers.html )

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, January 10, 2016 5:20 PM