We help IT Professionals succeed at work.

using using {...} in C#. How to use?

jazzIIIlove
jazzIIIlove asked
on
Hi there:

I want to use  using {...} in C#. How to use? What should I do? What is the restrictions?

Kind regards.
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
How to use? What should I do?
You simply include a declaration of an object you want to use within that block. For example, you can put your SqlConnection objects in a using:

using (SqlConnection con = new SqlConnection(some_con_str))
{
    // Use "con" within this block. It will cease to exist once the block exits
}

Open in new window


What is the restrictions?

Open in new window

You can only use using blocks with types that implement the IDisposable interface, since a using implicitly calls the Dispose method of the object for you. You next question might be, "How do I know if a class implements the IDisposable interface?" The answer is quite simple: either consult the documentation, view the definition within the meta data (i.e. use "Go to Definition"), or simply try creating a using block with your desired type--if the type does not implement IDisposable, then the IDE will let you know.
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
Alternatively, if the class has a Dispose method, then more than likely it implements IDisposable. Also, you don't have to declare the variable within the using as I did above, however, the Dispose will always be called. Even if you declare the object outside of the using, once it exits that block, the object may be in an unstable state based on whatever happens in the object's respective Dispose method.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.