Baran Topal

Baran Topal


April 2024
M T W T F S S
« Feb    
1234567
891011121314
15161718192021
22232425262728
2930  

Categories


using {…} in C#

baranbaran

How to use:

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
}

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.