Is there any specific technical difference in between doing this...
using OtraLibreria;
namespace Libreria {
class MiClase {
/// mas código aqui
}
}
and this other?
namespace Libreria {
using OtraLibreria;
class MiClase {
/// mas código aqui
}
}
Yes there is a slight difference between the two. Imagine you have the following code in
File1.cs
:Now imagine that someone adds another file
File2.cs
that looks like this to the project:The compiler searches
Externo
before lookingusing
outside the namespace, so it findsExterno.Math
instead ofSystem.Math
. Unfortunately (or perhaps fortunately),Externo.Math
it doesn't have any members namedPI
, so itFile1.cs
doesn't compile.This changes if you put the
using
inside the namespace like so:Now the compiler looks in
System
beforeExterno
, finds it,System.Math
and everything works.Some would argue that it
Math
may be a bad name for a user defined class since one already exists inSystem
but the point is that there is a difference and it does affect the maintainability of the code.It's also interesting to note what happens if it
Foo
's in the namespaceExterno
instead ofExterno.Interno
. In that case addingExterno.Math
in File2 makes it not compile no matter where theusing
. This means that the compiler looks for the innermost namespace before looking inside anyusing
.The difference is that you can reduce the length of the inclusion of nested namespaces. For example:
If you had it globally, outside of the namespace, it would affect all the namespaces that are inside that file. Example:
For more brief information on the subject, read this: using (Directive)
Another point to note is that a directive
using
within a blocknamespace
is local to that block and overrides external definitions.For example, suppose you have the classes
A.MiClase
,B.MiClase
andC.MiClase
. Then:As I remember, if we put the using inside the namespace, it will load the referenced assembly only when it is called. That is, when the class that uses it is loaded and launched.
Putting the using outside of the namespace will load the assembly when the main assembly is loaded.
This is very important in terms of performance and memory consumption.