Wednesday, April 24, 2019

scope - C# - Location of using statements

Answer


Answer




One thing I have noticed a lot of back and forth on is where using statements should be placed in a C# code file- whether its in the outermost scope or inside a namespace. I understand that the location of the using statement affects the scope of the references within that file, but what I don't understand is why, in most cases, someone would ever want their using statements inside their namespace.



In almost all cases only one namespace declaration ever exists in a single file so scoping the using statements seems/(is?) useless. If one were placing multiple types and multiple namespaces in the same file then scoped using statements make perfect sense, yet I still see plenty of cases of this being done even in files with one namespace. Why?



using System;


namespace MyNamespace
{
using System.Text;

public class MyClass {
// ...
}
}



An example of this being done throughout a project seemingly unnecessarily is the ASP.NET MVC source.


Answer



Putting "using" at the top of the files is the default way of Visual Studio. However, the recommended approach is putting the "using" statements inside of the namespace. Even MS's stylecop catches this and says the default way of VS is wrong.



Both techniques work fine.




StyleCop Rule says:
Placing multiple namespace elements

within a single file is generally a
bad idea, but if and when this is
done, it is a good idea to place all
using directives within each of the
namespace elements, rather than
globally at the top of the file. This
will scope the namespaces tightly, and
will also help to avoid the kind of
behavior described above.




It is important to note that when code
has been written with using directives
placed outside of the namespace, care
should be taken when moving these
directives within the namespace, to
ensure that this is not changing the
semantics of the code. As explained
above, placing using-alias directives
within the namespace element allows
the compiler to choose between

conflicting types in ways that will
not happen when the directives are
placed outside of the namespace.




Here's some links for further review:




No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...