Home >Backend Development >C++ >Should C# `using` Directives Be Inside or Outside the Namespace?
C#
Instruction: Is it the name space within the name space?
using
STYLECOP recommends instructions in the name space statement. Although there is no direct technical reason for this, it will have a slight impact on the maintenance of the code.
Consider two files in a C# project: file1 and file2. In File1, instructions are used for System.math and placed outside the name space. using
Now, suppose File2 introduces a user -defined class called OUTER.MATH. The compiler searches for naming space before searching instructions, and it will give priority to selecting OUTER.MATH instead of System.math. If OUTER.MATH does not have PI members like System.math, File1 will be invalid. using
<code class="language-csharp">// File1.cs using System; namespace Outer.Inner { // ... }</code>
using
Now, the compiler searches System before Outr, finds System.math and avoids this problem.
Although some people think that because of the existence of System.math, it is not wise to use Math as a class name, but this example highlights the subtle difference between placing using
in the name space or the name space. This difference can also affect the maintenance of the code.
<code class="language-csharp">// File1b.cs namespace Outer.Inner { using System; // ... }</code>In addition, if the FOO is located in the OUTER naming space rather than the Outr.inner name space, no matter what the
instruction is, the addition of Outr.math to the File2 will destroy File1. This means that the compiler searches the innermost layer of name space before checking the
instruction.The above is the detailed content of Should C# `using` Directives Be Inside or Outside the Namespace?. For more information, please follow other related articles on the PHP Chinese website!