Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"using" statement locations within namespace declarations [duplicate]

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
{
like image 833
Phil.Wheeler Avatar asked May 13 '11 02:05

Phil.Wheeler


People also ask

Should using be inside or outside namespace?

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.).

What is the purpose of the using directive?

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.

What is a file scoped namespace?

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.

What is a compilation unit C#?

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.


2 Answers

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.

like image 60
Adam Maras Avatar answered Sep 29 '22 04:09

Adam Maras


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.

like image 37
Jordão Avatar answered Sep 29 '22 03:09

Jordão