Possible Duplicate:
Should Usings be inside or outside the namespace
I'm supporting some code that, unusually, has all its using statements contained within the namespace declaration. It makes me a bit uncomfortable but I have no idea if this should be anything to be concerned about or not. I can't think of an immediate problem other than it being counter to usual convention.
Is there anything wrong with:
namespace myProject.controls
{
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
Instead of the more widely-used:
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace myProject.controls
{
You cannot have a using directive inside a class as you indicate. It must be on a namespace level, for example outside the outermost namespace , or just inside the innermost namespace (but not inside a class/interface/etc.).
The primary function of the using directive is to make types within a namespace available without qualification to the user code. It considers the set of namespaces and types which are defined in referenced assemblies and the project being compiled.
File Scoped Namespace is a new feature of C# 10. The idea is to remove one level of indentation from source files when they contain only one namespace in it. The goal is to reduce horizontal and vertical scrolling and make the code more readable.
A compilation unit is C source code that is compiled and treated as one logical unit. The compilation unit is usually one or more entire files, but can also be a selected portion of a file if, for example, the #ifdef preprocessor directive is used to select specific code sections.
There's nothing to be concerned with here; in fact, the first example (with the using
statements inside the namespace declaration) is recommended by default by StyleCop.
The only difference has to do with scoping. In the first case, the using declarations are scoped within the namespace declaration, and are not available outside it, in other namespace declarations in the same file, for example. In the second case, the declarations are in scope for the whole file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With