blah blah blah is here! blah blah » Close

up0down
link

hi this is stalin
in my project iam using using() method in somepage,but i dotn't know the usage of that one,can anybody know this sol please explain me.....
using ((con))
{
try
{
con.Bind();
}
catch (LdapException le)
{
lblresult = "Invalid server address or admin password";
return;
}
catch (DirectoryOperationException doe)
{
lblresult = "Invalid admin username";
return;
}
try
{
SearchRequest Request = new SearchRequest("ou=kaps,o=npcil,c=in", string.Format("(employeenumber=" + emp_no + ")"), SearchScope.Subtree);
SearchResponse response1 = (SearchResponse)con.SendRequest(Request);
if ((response1.Entries.Count == 0))
{
lblresult = "No such username.";
return;
}
else
{
SearchResultEntry entry = response1.Entries[0];
uid = entry.Attributes["uid"][0].ToString();
pass = entry.Attributes["userpassword"][0].ToString();
}
}

last answered 2 years ago

1 answers

up0down
link

The idea of the using() statement is to take an object which implements the IDisposable interface and ensure that Dispose() will be called on that object whatever may happen within the using() statement itself.
In particular, Dispose() will still be called even if an exception occurs whilst the code within the using() block is being executed.
An object should implement IDisposable where it needs to release unmanaged resources (file handles, database connections etc) prior to destruction.
Normally, the object variable should be declared and instantiated within the using() header. It will then go out of scope as soon as Dispose() has been called.
If you declare and instantiate the object variable <b>outside</b> the using() statement, then the variable will still be in scope when the using() statment ends but will refer to a disposed object. Attempting to use that object will probably then throw an exception.
That's precisely what's happening here - the 'con' variable has been declared and instantiated outside the using() statement. Now that's probably OK if an exception occurs causing the enclosing method to return, but may not be OK if an exception doesn't occur.
If you might still want to use 'con' after the using() statement has ended, I wouldn't use using() - I'd tack on a 'finally' block after your catch blocks which includes the statement:
con.Dispose();

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback