c# - While disposing the class instance, do i need to dispose all its IDisposable members explicitly? -


i have class has property of type sqlconnection. sqlconnection implements idisposable. have following questions:

  1. should class implement idisposable because has property of type idisposable?
  2. if yes, need dispose property explicitly when disposing instance of class? e.g.

    public class helper : idisposable {     // assume it's other idisposable type. sqlconnection example.     public sqlconnection sqlconnection { get; set; }      public void dispose()     {         if (sqlconnection!= null)         {             sqlconnection.dispose();         }     } } 

note : know there pattern followed while implementing idisposable question specific case mentioned above.

it depends. if class creates , owns idisposable must dispose (so, both answers "yes"). if class uses idisposable must not dispose (so first answer is, usually, "no" , second answer "no").

in case, seems helper class

  public class helper   {       // note, can assign arbitrary connection via property       public sqlconnection sqlconnection { get; set; }       ....   } 

just uses sqlconnection (because provides "set") in way like

// it's not helper owns sqlconnection using (sqlconnection con = new sqlconnection(...)) {   ...   // helper uses connection, helper must not dispose   helper helper = new helper() {     sqlconnection = con;    };    ... } 

so must not dispose connection. on contrary, class that

public class helper: idisposable {   private sqlconnection m_sqlconnection;    // note absence of public "set"   public sqlconnection sqlconnection {     {       return m_sqlconnection;      }    }   ... }   

owns sqlconnection it's responsible disposing it:

using (helper helper = new helper(...)) {   ...   // it's helper owns sqlconnection   sqlconnection con = helper.sqlconnection;   ... }  

Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -