views:

727

answers:

6

Right, I've usually used 'using' directives as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AwesomeLib
{
  //awesome award winning class declarations making use of Linq
}

i've recently seen examples of such as

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AwesomeLib
{
  //awesome award winning class declarations making use of Linq

  namespace DataLibrary
  {
    using System.Data;

    //Data access layers and whatnot
  }

}

Granted, i understand that i can put USING inside of my namespace declaration. Such a thing makes sense to me if your namespaces are in the same root (they organized).

System;
namespace 1 {}
namespace 2 
{
  System.data;
}

But what of nested namespaces? Personally, I would leave all USING declarations at the top where you can find them easily. Instead, it looks like they're being spread all over the source file.

Is there benefit to the USING directives being used this way in nested namespaces? Such as memory management or the JIT compiler?

+3  A: 

When you are in a scope that doesn't need System.Data it is better if the IntelliSense doesn't trigger the System.Data members just to mess with other things you are looking for

About some performance issue - I don't think it matters how you prefer to use it...

Svetlozar Angelov
+3  A: 

There's no benefit to the generated intermediate language. Since the CIL is the input for the JIT compiler, this is also unaffected.

Since you're speaking about best practises: it's best practise is to have only one class per file, so you'd have only one namespace as well.

Thorarin
A: 

The using clauses only help making your code more maintainable, they don't affect the performance of your code AFAIK.

The same applies to namespaces - you could put all your classes in the global namespace and name them Class1, Class2 and so on, and your code would perform just as well. But it would be a nightmare to maintain!

So they are both there to help you, the coder, they don't affect the compiled code.

Rune Grimstad
+1  A: 

From the Style Cop rules:

  1. Placing using-alias directives within the namespace eliminates compiler confusion between conflicting types.
  2. When multiple namespaces are defined within a single file, placing using directives within the namespace elements scopes references and aliases.
jbloomer
+5  A: 
John K
A: 

Is out of argument, but using directive its used also for defines a scope, outside of which an object or objects will be disposed.

using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString){//close connection is not more necessary}
Shammy