Should an outer using directive encase an immediately-following inner using directive in curly braces?

StackOverflow https://stackoverflow.com/questions/19596698

Question

I'm getting an exception (which is not being logged either by the catch block in the method where it seems to be happening OR in the global exception handler I've added) after a while loop terminates (no more records are read).

In debugging this, gazing intently at this code, I began to wonder if it should remain:

using (var conn = new OleDbConnection(
   @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Platydude;Password=Platypup;Data  
   Source=C:\Duckbill\DATA\DuckbillDAT03.MDB;Jet OLEDB:System 
   database=C:\Duckbill\Data\platypus.mdw"))
{
    using (var cmd = conn.CreateCommand())
    {
        . . .
    }
}

...or be simply:

using (var conn = new OleDbConnection(
   @"Provider=Microsoft.Jet.OLEDB.4.0;User ID=Platydude;Password=Platypup;Data  
   Source=C:\Duckbill\DATA\DuckbillDAT03.MDB;Jet OLEDB:System 
   database=C:\Duckbill\Data\platypus.mdw"))
using (var cmd = conn.CreateCommand())
{
    . . .
}

Does it make any difference? It doesn't seem to - either way the exact same thing happens; but is there a scenario where one way is safer than the other? IOW: which one is the preferred technique?

Was it helpful?

Solution

Functionally, they are the same. Stylistically, I prefer the latter (as do most people, from what I've seen), since it eliminates unnecessary braces and indentations, and reads more naturally (like it's saying "using this and that" instead of "using this { using that { ").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top