<p>User <a href="https://stackoverflow.com/users/1065/kokos">kokos</a> answered the wonderful <em><a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a></em> question by mentioning the <code>using</code> keyword. Can you elaborate on that? What are the uses of <code>using</code>?</p>

[{'answer_id': 75419, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 2, 'selected': False, 'text': '<p>When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.</p>\n'}, {'answer_id': 75426, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 7, 'selected': False, 'text': '<p>Things like this:</p>\n\n<pre><code>using (var conn = new SqlConnection("connection string"))\n{\n   conn.Open();\n\n    // Execute SQL statement here on the connection you created\n}\n</code></pre>\n\n<p>This <code>SqlConnection</code> will be closed without needing to explicitly call the <code>.Close()</code> function, and this will happen <em>even if an exception is thrown</em>, without the need for a <code>try</code>/<code>catch</code>/<code>finally</code>.</p>\n'}, {'answer_id': 75435, 'author': 'Gilligan', 'author_id': 12356, 'author_profile': 'https://Stackoverflow.com/users/12356', 'pm_score': 0, 'selected': False, 'text': '<p>The <a href="http://web.archive.org/web/20080809044303/http://www.ayende.com:80/Wiki/Rhino%20Mocks%20Record-playback%20Syntax.ashx" rel="nofollow noreferrer">Rhino Mocks Record-playback Syntax</a> makes an interesting use of <code>using</code>.</p>\n'}, {'answer_id': 75443, 'author': 'Grank', 'author_id': 12975, 'author_profile': 'https://Stackoverflow.com/users/12975', 'pm_score': 1, 'selected': False, 'text': "<p>When you use <em>using</em>, it will call the Dispose() method on the object at the end of the using's scope.  So you can have quite a bit of great cleanup code in your Dispose() method.</p>\n<p>A bullet point:</p>\n<p>If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.</p>\n"}, {'answer_id': 75444, 'author': 'MagicKat', 'author_id': 8505, 'author_profile': 'https://Stackoverflow.com/users/8505', 'pm_score': 5, 'selected': False, 'text': '<p><em>using</em> can be used to call IDisposable.  It can also be used to alias types.</p>\n<pre><code>using (SqlConnection cnn = new SqlConnection()) { /* Code */}\nusing f1 = System.Windows.Forms.Form;\n</code></pre>\n'}, {'answer_id': 75451, 'author': 'David Arno', 'author_id': 7122, 'author_profile': 'https://Stackoverflow.com/users/7122', 'pm_score': 2, 'selected': False, 'text': '<p>&quot;using&quot; can also be used to resolve namespace conflicts.</p>\n<p>See <em><a href="http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/" rel="nofollow noreferrer">http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/</a></em> for a short tutorial I wrote on the subject.</p>\n'}, {'answer_id': 75461, 'author': 'David Basarab', 'author_id': 2469, 'author_profile': 'https://Stackoverflow.com/users/2469', 'pm_score': 1, 'selected': False, 'text': '<p>The <em>using</em> keyword defines the scope for the object and then disposes of the object when the scope is complete.  For example.</p>\n<pre><code>using (Font font2 = new Font(&quot;Arial&quot;, 10.0f))\n{\n    // Use font2\n}\n</code></pre>\n<p>See <a href="http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx" rel="nofollow noreferrer">here</a> for the MSDN article on the C# <em>using</em> keyword.</p>\n'}, {'answer_id': 75480, 'author': 'Bob Wintemberg', 'author_id': 12999, 'author_profile': 'https://Stackoverflow.com/users/12999', 'pm_score': 2, 'selected': False, 'text': "<p><strong>using</strong> is used when you have a resource that you want disposed after it's been used.</p>\n<p>For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.</p>\n<p>The resource being used needs to implement IDisposable to work properly.</p>\n<p>Example:</p>\n<pre><code>using (File file = new File (parameters))\n{\n    // Code to do stuff with the file\n}\n</code></pre>\n"}, {'answer_id': 75483, 'author': 'paulwhit', 'author_id': 7301, 'author_profile': 'https://Stackoverflow.com/users/7301', 'pm_score': 10, 'selected': True, 'text': '<p>The reason for the <code>using</code> statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn\'t require explicit code to ensure that this happens.</p>\n\n<p>As in <em><a href="https://www.codeproject.com/Articles/6564/Understanding-the-using-statement-in-C" rel="noreferrer">Understanding the \'using\' statement in C# (codeproject)</a></em> and <em><a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects" rel="noreferrer">Using objects that implement IDisposable (microsoft)</a></em>, the C# compiler converts</p>\n\n<pre><code>using (MyResource myRes = new MyResource())\n{\n    myRes.DoSomething();\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>{ // Limits scope of myRes\n    MyResource myRes= new MyResource();\n    try\n    {\n        myRes.DoSomething();\n    }\n    finally\n    {\n        // Check for a null resource.\n        if (myRes != null)\n            // Call the object\'s Dispose method.\n            ((IDisposable)myRes).Dispose();\n    }\n}\n</code></pre>\n\n<p>C# 8 introduces a new syntax, named "<a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations" rel="noreferrer">using declarations</a>":</p>\n\n<blockquote>\n  <p>A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.</p>\n</blockquote>\n\n<p>So the equivalent code of above would be:</p>\n\n<pre><code>using var myRes = new MyResource();\nmyRes.DoSomething();\n</code></pre>\n\n<p>And when control leaves the containing scope (usually a method, but it can also be a code block), <code>myRes</code> will be disposed.</p>\n'}, {'answer_id': 75497, 'author': 'Joel Martinez', 'author_id': 5416, 'author_profile': 'https://Stackoverflow.com/users/5416', 'pm_score': 2, 'selected': False, 'text': '<p>Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it).  Basically, you can take advantage of the fact that the compiler will <strong>always</strong> call .Dispose on the "used" object.  If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.</p>\n\n<p>This allows you to use the really nice using syntax to denote the explicit start and end of said operation.  This is also how the System.Transactions stuff works.</p>\n'}, {'answer_id': 75516, 'author': 'Sam Schutte', 'author_id': 146, 'author_profile': 'https://Stackoverflow.com/users/146', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve used it a lot in the past to work with input and output streams.  You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose).  For example:</p>\n\n<pre><code>        using (FileStream fs = new FileStream("c:\\file.txt", FileMode.Open))\n        {\n            using (BufferedStream bs = new BufferedStream(fs))\n            {\n                using (System.IO.StreamReader sr = new StreamReader(bs))\n                {\n                    string output = sr.ReadToEnd();\n                }\n            }\n        }\n</code></pre>\n'}, {'answer_id': 75640, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>Not that it is ultra important, but <em>using</em> can also be used to change resources on the fly.</p>\n<p>Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.</p>\n"}, {'answer_id': 75867, 'author': 'BlackTigerX', 'author_id': 8411, 'author_profile': 'https://Stackoverflow.com/users/8411', 'pm_score': 7, 'selected': False, 'text': '<p>Since a lot of people still do:</p>\n\n<pre><code>using (System.IO.StreamReader r = new System.IO.StreamReader(""))\nusing (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {\n   //code\n}\n</code></pre>\n\n<p>I guess a lot of people still don\'t know that you can do:</p>\n\n<pre><code>using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {\n   //code\n}\n</code></pre>\n'}, {'answer_id': 76192, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 2, 'selected': False, 'text': '<p>In conclusion, when you use a local variable of a type that implements <code>IDisposable</code>, <em>always</em>, without exception, use <code>using</code><sup>1</sup>.</p>\n\n<p>If you use nonlocal <code>IDisposable</code> variables, then <em>always</em> implement the <a href="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="noreferrer"><code>IDisposable</code> pattern</a>.</p>\n\n<p>Two simple rules, no exception<sup>1</sup>. Preventing resource leaks otherwise is a real pain in the *ss.</p>\n\n<hr>\n\n<p><sup>1)</sup>: The only exception is –\xa0when you\'re handling exceptions. It might then be less code to call <code>Dispose</code> explicitly in the <code>finally</code> block.</p>\n'}, {'answer_id': 76232, 'author': 'Brendan Kendrick', 'author_id': 13473, 'author_profile': 'https://Stackoverflow.com/users/13473', 'pm_score': 1, 'selected': False, 'text': '<p>Another example of a reasonable use in which the object is immediately disposed:</p>\n\n<pre><code>using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) \n{\n    while (myReader.Read()) \n    {\n        MyObject theObject = new MyObject();\n        theObject.PublicProperty = myReader.GetString(0);\n        myCollection.Add(theObject);\n    }\n}\n</code></pre>\n'}, {'answer_id': 76278, 'author': 'Lucas', 'author_id': 5966, 'author_profile': 'https://Stackoverflow.com/users/5966', 'pm_score': 3, 'selected': False, 'text': '<p>Another great use of <em>using</em> is when instantiating a modal dialog.</p>\n<pre class="lang-vbnet prettyprint-override"><code>Using frm as new Form1\n\n    Form1.ShowDialog\n\n    \' Do stuff here\n\nEnd Using\n</code></pre>\n'}, {'answer_id': 204957, 'author': 'Amanda Mitchell', 'author_id': 26628, 'author_profile': 'https://Stackoverflow.com/users/26628', 'pm_score': 4, 'selected': False, 'text': '<p><em>using</em>, in the sense of</p>\n<pre><code>using (var foo = new Bar())\n{\n  Baz();\n}\n</code></pre>\n<p>Is actually shorthand for a try/finally block. It is equivalent to the code:</p>\n<pre><code>var foo = new Bar();\ntry\n{\n  Baz();\n}\nfinally\n{\n  foo.Dispose();\n}\n</code></pre>\n<p>You\'ll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we\'ve come up with a class that we call <em>Scope</em> that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you\'d do it like this:</p>\n<pre><code>using (new Scope(() =&gt; IsWorking = false))\n{\n  IsWorking = true;\n  MundaneYetDangerousWork();\n}\n</code></pre>\n<p>You can read more about our solution and how we derived it <a href="https://faithlife.codes/blog/2008/08/leverage_using_blocks_with_scope/" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 204987, 'author': 'milot', 'author_id': 22637, 'author_profile': 'https://Stackoverflow.com/users/22637', 'pm_score': 1, 'selected': False, 'text': "<p>Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:</p>\n\n<pre><code>using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))\n{\n   // do stuff\n} // here adapter_object is disposed automatically\n</code></pre>\n"}, {'answer_id': 13175552, 'author': 'Shiraj Momin', 'author_id': 1787655, 'author_profile': 'https://Stackoverflow.com/users/1787655', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public class ClassA:IDisposable\n{\n    #region IDisposable Members\n    public void Dispose()\n    {\n        GC.SuppressFinalize(this);\n    }\n    #endregion\n}\n</code></pre>\n<hr />\n<pre><code>public void fn_Data()\n{\n    using (ClassA ObjectName = new ClassA())\n    {\n        // Use objectName\n    }\n}\n</code></pre>\n'}, {'answer_id': 20271484, 'author': 'Riya Patil', 'author_id': 2191381, 'author_profile': 'https://Stackoverflow.com/users/2191381', 'pm_score': -1, 'selected': False, 'text': '<p>The <em>using</em> clause is used to define the scope for the particular variable.</p>\n<p>For example:</p>\n<pre><code>Using(SqlConnection conn = new SqlConnection(ConnectionString)\n{\n    Conn.Open()\n\n    // Execute SQL statements here.\n    // You do not have to close the connection explicitly\n    // here as &quot;USING&quot; will close the connection once the\n    // object Conn goes out of the defined scope.\n}\n</code></pre>\n'}, {'answer_id': 22994945, 'author': 'VictorySaber', 'author_id': 2878135, 'author_profile': 'https://Stackoverflow.com/users/2878135', 'pm_score': 3, 'selected': False, 'text': '<p>You can make use of the alias namespace by way of the following example:</p>\n\n<pre><code>using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;\n</code></pre>\n\n<p>This is called a <em>using alias directive</em> as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to\ne.g.</p>\n\n<pre><code>LegacyEntities.Account\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account\n</code></pre>\n\n<p>or simply</p>\n\n<pre><code>Account   // It is not obvious this is a legacy entity\n</code></pre>\n'}, {'answer_id': 29407147, 'author': 'snowell', 'author_id': 3720990, 'author_profile': 'https://Stackoverflow.com/users/3720990', 'pm_score': 1, 'selected': False, 'text': '<p>The <em>using</em> statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.</p>\n<p>The <em>using</em> statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the <em>using</em> block, the object is read-only and cannot be modified or reassigned.</p>\n<p>This comes from <a href="https://social.msdn.microsoft.com/Search/en-US?query=using&amp;emptyWatermark=true&amp;ac=4" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 29897282, 'author': 'Seb', 'author_id': 4693156, 'author_profile': 'https://Stackoverflow.com/users/4693156', 'pm_score': 1, 'selected': False, 'text': '<p>For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.</p>\n\n<p>A different name for error handling would\'ve been nice, and maybe a somehow more obvious one.</p>\n'}, {'answer_id': 29897576, 'author': 'Pluc', 'author_id': 1338607, 'author_profile': 'https://Stackoverflow.com/users/1338607', 'pm_score': 3, 'selected': False, 'text': "<p>Just adding a little something that I was surprised did not come up. The most interesting feature of <em>using</em> (in my opinion) is that no matter how you exit the <em>using</em> block, it will always dispose the object. This includes returns and exceptions.</p>\n<pre><code>using (var db = new DbContext())\n{\n    if(db.State == State.Closed)\n        throw new Exception(&quot;Database connection is closed.&quot;);\n    return db.Something.ToList();\n}\n</code></pre>\n<p>It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.</p>\n"}, {'answer_id': 34465332, 'author': 'Aureliano Buendia', 'author_id': 738587, 'author_profile': 'https://Stackoverflow.com/users/738587', 'pm_score': 4, 'selected': False, 'text': '<p>Microsoft documentation states that <strong>using</strong> has a double function (<a href="https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx</a>), both as a <em>directive</em> and in <em>statements</em>. As a <em>statement</em>, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an <strong>IDisposable</strong> object. As a <em>directive</em>, it is routinely used to import namespaces and types. Also as a directive, you can create <em>aliases</em> for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (<a href="https://rads.stackoverflow.com/amzn/click/com/B008E6I1K8" rel="noreferrer" rel="nofollow noreferrer">http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8</a>),  by Joseph and Ben Albahari. One example:</p>\n\n<pre><code>namespace HelloWorld\n{\n    using AppFunc = Func&lt;IDictionary&lt;DateTime, string&gt;, List&lt;string&gt;&gt;;\n    public class Startup\n    {\n        public static AppFunc OrderEvents() \n        {\n            AppFunc appFunc = (IDictionary&lt;DateTime, string&gt; events) =&gt;\n            {\n                if ((events != null) &amp;&amp; (events.Count &gt; 0))\n                {\n                    List&lt;string&gt; result = events.OrderBy(ev =&gt; ev.Key)\n                        .Select(ev =&gt; ev.Value)\n                        .ToList();\n                    return result;\n                }\n                throw new ArgumentException("Event dictionary is null or empty.");\n            };\n            return appFunc;\n        }\n    }\n}\n</code></pre>\n\n<p>This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one\'s code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (<a href="http://www.dotnetperls.com/using-alias" rel="noreferrer">http://www.dotnetperls.com/using-alias</a>).</p>\n'}, {'answer_id': 41463137, 'author': 'Siamand', 'author_id': 2276651, 'author_profile': 'https://Stackoverflow.com/users/2276651', 'pm_score': 1, 'selected': False, 'text': '<p>It also can be used for creating scopes for Example:</p>\n\n<pre><code>class LoggerScope:IDisposable {\n   static ThreadLocal&lt;LoggerScope&gt; threadScope = \n        new ThreadLocal&lt;LoggerScope&gt;();\n   private LoggerScope previous;\n\n   public static LoggerScope Current=&gt; threadScope.Value;\n\n   public bool WithTime{get;}\n\n   public LoggerScope(bool withTime){\n       previous = threadScope.Value;\n       threadScope.Value = this;\n       WithTime=withTime;\n   }\n\n   public void Dispose(){\n       threadScope.Value = previous;\n   }\n}\n\n\nclass Program {\n   public static void Main(params string[] args){\n       new Program().Run();\n   }\n\n   public void Run(){\n      log("something happend!");\n      using(new LoggerScope(false)){\n          log("the quick brown fox jumps over the lazy dog!");\n          using(new LoggerScope(true)){\n              log("nested scope!");\n          }\n      }\n   }\n\n   void log(string message){\n      if(LoggerScope.Current!=null){\n          Console.WriteLine(message);\n          if(LoggerScope.Current.WithTime){\n             Console.WriteLine(DateTime.Now);\n          }\n      }\n   }\n\n}\n</code></pre>\n'}, {'answer_id': 49166602, 'author': 'deepak samantaray', 'author_id': 4661703, 'author_profile': 'https://Stackoverflow.com/users/4661703', 'pm_score': 1, 'selected': False, 'text': "<p>The <em>using</em> statement tells .NET to release the object specified in the <em>using</em> block once it is no longer needed.</p>\n<p>So you should use the 'using' block for classes that require cleaning up after them, like <em>System.IO</em> types.</p>\n"}, {'answer_id': 50293207, 'author': 'Vazgen Torosyan', 'author_id': 3541666, 'author_profile': 'https://Stackoverflow.com/users/3541666', 'pm_score': 0, 'selected': False, 'text': '<blockquote>\n<p>using as a statement automatically calls the dispose on the specified\nobject. The object must implement the IDisposable interface. It is\npossible to use several objects in one statement as long as they are\nof the same type.</p>\n</blockquote>\n<p>The <a href="https://en.wikipedia.org/wiki/Common_Language_Runtime" rel="nofollow noreferrer">CLR</a> converts your code into <a href="https://en.wikipedia.org/wiki/Common_Intermediate_Language" rel="nofollow noreferrer">CIL</a>. And the <em>using</em> statement gets translated into a try and finally block. This is how the <em>using</em> statement is represented in CIL. A <em>using</em> statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a <em>try</em> statement with a <em>finally</em> clause. The object then gets disposed in the <em>finally</em> clause.</p>\n'}, {'answer_id': 51590168, 'author': 'Chamila Maddumage', 'author_id': 8194089, 'author_profile': 'https://Stackoverflow.com/users/8194089', 'pm_score': 2, 'selected': False, 'text': '<p>There are two usages of the <code>using</code> keyword in C# as follows.</p>\n<ol>\n<li><p>As a directive</p>\n<p>Generally we use the <code>using</code> keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.</p>\n<p>Example:</p>\n<pre><code>using System.IO;\n</code></pre>\n</li>\n<li><p>As a statement</p>\n<p>This is another way to use the <code>using</code> keyword in C#. It plays a vital role in improving performance in garbage collection.</p>\n<p>The <code>using</code> statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.</p>\n<p>Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.</p>\n<p>You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.</p>\n<p>Example:</p>\n<pre><code>string connString = &quot;Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;&quot;;\n\nusing (SqlConnection conn = new SqlConnection(connString))\n{\n      SqlCommand cmd = conn.CreateCommand();\n      cmd.CommandText = &quot;SELECT CustomerId, CompanyName FROM Customers&quot;;\n      conn.Open();\n      using (SqlDataReader dr = cmd.ExecuteReader())\n      {\n         while (dr.Read())\n         Console.WriteLine(&quot;{0}\\t{1}&quot;, dr.GetString(0), dr.GetString(1));\n      }\n}\n</code></pre>\n</li>\n</ol>\n<p>In the preceding code I am not closing any connection; it will close automatically. The <code>using</code> statement will call conn.Close() automatically due to the <code>using</code> statement (<code>using (SqlConnection conn = new SqlConnection(connString)</code>) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.</p>\n<p>For more information, see <em><a href="https://www.c-sharpcorner.com/UploadFile/manas1/usage-and-importance-of-using-in-C-Sharp472/" rel="nofollow noreferrer">Usage and Importance of Using in C#</a></em>.</p>\n'}]
['https://Stackoverflow.com/questions/75401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13332/']