c# - How to return an object that's dependent on a chain of using statements? -


i'd write method similar one:

c make() {     using (var = new a())     using (var b = new b(a))     {         return new c(b);     } } 

this bad since when method returns, c keeps reference disposed object.

note that:

  • a implements idisposable.
  • b implements idisposable.
  • c not implement idisposable since author of c stated c not take ownership of b.

your situation similar have seen when querying database. in attempt separate logic, see code this:

var reader = executesql("select ..."); while (reader.read()) // <-- fails, because connection closed. {     // process row... }  public sqldatareader executesql(string sql) {     using (sqlconnection conn = new sqlconnection("..."))     {         conn.open();         using (sqlcommand cmd = new sqlcommand(sql, conn))         {             return cmd.executereader();         }     } } 

but, of course, can't work, because time sqldatareader returns executesql method, connection closed (disposed).

so alternative above makes use of delegates achieve separation of concerns, still allowing code work properly:

executesql(reader => {     // write code reads sqldatareader here. });  public void executesql(string sql, action<sqldatareader> processrow) {     using (sqlconnection conn = new sqlconnection("..."))     {         conn.open();         using (sqlcommand cmd = new sqlcommand(sql, conn))         {             using (sqldatareader reader = cmd.executereader())             {                 while (reader.read())                 {                     processrow(reader);                 }             }         }     } } 

so, perhaps can try similar in case? this:

makeandprocess(c => {     // write code uses c here.     // work, because , b not disposed yet. });  public void makeandprocess(action<c> processc) {     using (var = new a())     using (var b = new b(a))     {         processc(new c(b));     } } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -