The placement of USING instructions in C#: Considering factors
When analyzing the C# code with Stylecop, you may receive a warning about placing the USING instruction inside the name space. The question is: Is there a technical reason for this?
The influence of placing
Putting the USING instruction inside or outside the naming space may subtly change the code behavior. Consider the following code structure:
If you add another file (File2.cs), it has the following content:
// File1.cs using System; namespace Outer.Inner { class Foo { static void Bar() { double d = Math.PI; } } }
When the USING instruction is outside the name space, the compiler will give priority to Outr.math instead of system.math, because the lack of PI members in the outer.math causes code interruption.
// File2.cs namespace Outer { class Math { } }
By placing the USING instruction inside the name space, the order of the compiler will change. System.math is preferred by Out.math, which solves the problem of code interrupt.
<命> Naming space nested and placed
// File1b.cs namespace Outer.Inner { using System; class Foo { static void Bar() { double d = Math.PI; } } }
Conclusion
Although this may not be a key technical problem, placing the USING instruction inside the name space can be improved by clarifying the priority of members' analysis to improve the maintenance of the code. It can also ensure that your code conflicts with naming spaces that may cause accidental interruption.
The above is the detailed content of Should Using Directives Be Placed Inside or Outside Namespaces in C#?. For more information, please follow other related articles on the PHP Chinese website!