Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

What is the use of the following in asp.net. Please give an example of creating sql connection? using(resource){ }

user-image
Question added by Deleted user
Date Posted: 2014/10/02
sarfraz khan
by sarfraz khan , Software Engineer , Inspop.com Limited

This is only applicable for classes that implement IDisposable. It is helpful for cleaning up code where you have objects that take, for example, system resources (file handles, database connections, sockets, etc.) that need to be cleaned up after you are done to free the resource for the rest of the system.

In theory, you could leave out the .Dispose() call, but then you would have to wait for the Garbage Collector to free the kept resources. The GC is awesome at knowing when to free objects to reclaim their memory usage, but it has no idea that it needs to free objects to have them give up other system resources. Thus, these critical resources might not be given up until after the GC decides it needs the memory used by the owner. Thus, you definitely want to dispose of your objects when you are done with them (if they are disposable)!

As to why you'd use using over try/finally, it is purely a coder's preference. I prefer usingbecause you can cascade them:

 

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.