c# - Where should I put this using statement? -


i'm working system.directoryservices , have following method use create directoryentry:

static directoryentry createdirectoryentry(string connectionpath) {     directoryentry ldapconnection = null;      try     {         ldapconnection = new directoryentry(ad_domain_name))         ldapconnection.path = connectionpath;         ldapconnection.authenticationtype = authenticationtypes.secure;     }      catch (exception ex)     {         messagebox.show("exception caught in createdirectoryentry():\n\n" + ex.tostring());     }      return ldapconnection; }  

this method called in manner:

directoryentry ldapconnection = createdirectoryentry("ldap://ou=example,dc=domain,dc=com"); 

i read best practice use using statement implements idisposable. question is, need using statement in createdirectoryentry() method or should each call?

to illustrate mean, sufficient?:

static directoryentry createdirectoryentry(string connectionpath) {     directoryentry ldapconnection = null;      try     {         using (ldapconnection = new directoryentry(ad_domain_name))         {             ldapconnection.path = connectionpath;             ldapconnection.authenticationtype = authenticationtypes.secure;         }     }      catch (exception ex)     {         messagebox.show("exception caught in createdirectoryentry():\n\n" + ex.tostring());     }      return ldapconnection; }  

or need use using statement on call this?:

using (directoryentry ldapconnection = createdirectoryentry("ldap://ou=example,dc=domain,dc=com")) {     //do ldapconnection } 

any appreciated!

note: can't use system.directoryservices.accountmanagement solution please keep answers related system.directoryservices. thanks!

your last code-snippet way go, otherwise you'd returning disposed ldapconnection caller - not thing.

and +1 using using!!


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -