I am just curious to know why "using namespace" directive is acceptable in C#, though in C++ it is not. I am aware that C++ and C# are different, but my guess is C++ and C# come almost from same family, and should be using the same ideas for namespace resolution. C++ and C# both have an alias keyword to get around the namespace clash.
Can anybody point me, what I am not reading between lines in C# that makes it acceptable to use "using namespace" directive, and avoid the problems that C++ cannot.
Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.
The problem with putting using namespace in the header files of your classes is that it forces anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.
Need of namespace: As the same name can't be given to multiple variables, functions, classes, etc. in the same scope. So to overcome this situation namespace is introduced.
In C++, if you write using namespace
in a header, then it will be in effect for anyone who includes that header. This makes it pretty much unusable in headers. At that point, you might as well avoid it (at global scope) in .cpp files as well, if only for the sake of consistency, and to make moving implementations between .h and .cpp easier.
(note that locally scoped using namespace
- i.e. within a function - are generally considered fine; it's just that they don't help with verbosity much)
In C#, there is nothing like #include
, and the scope of a using
directive will never span beyond a single .cs file. So it's pretty much safe to use everywhere.
The other reason is the design of the standard library. In C++, you just have std
(well, now also a few more underneath it, but they are rarely used). In C#, you have gems such as System.Collections.Generic
, which is extremely verbose for something that's used very commonly. It's just much more painful to avoid using
in C# than it is in C++.
To sum it up, while C# and C++ do share some common design, on the matter of code modularity (I'd assign headers, modules, namespaces all to that group), their design is very different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With