11

Why is it that using namespace std; is considered poor practice in C++, but using System; is considered good practice in C#? They seem to be analogous (bringing standard library stuff into the global namespace).

Demi
  • 3,535
  • 5
  • 29
  • 45
  • 2
    Who says it's good practice in c#? – Ben Apr 17 '14 at 18:48
  • 1
    I would argue that `using namespace std;` is fine in implementation files; just keep it out of header files. However, there are nicer and more explicit alternatives like `using std::cout;` instead. – Suedocode Apr 17 '14 at 18:48
  • possible duplicate of [Why is "using namespace std;" considered bad practice?](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Deduplicator Apr 17 '14 at 18:51
  • MonoDevelop automatically includes it as the first line of any C# file – Demi Apr 17 '14 at 18:53
  • 3
    @Aggieboy And I would argue it is not "fine" in implementation files either (unless in a limited scope.) – juanchopanza Apr 17 '14 at 18:53
  • @juanchopanza Isn't a cpp file a form of limited scope? A `using namespace` *in a source file* is equivalent to a `using` directive in C# scope-wise. If someone shows that even this scope is too permissive, then perhaps. – Suedocode Apr 17 '14 at 20:02
  • @Aggieboy I mean scope more limited than a `.cpp` file. A function, for instance. – juanchopanza Apr 17 '14 at 20:16

2 Answers2

19

In C#, a using directive only impacts the file or namespace scope where it is placed.

If you include using namespace std; in a c++ header file, it impacts not only that file, but every file that includes it. This creates conflict potential in other people's files.

You could easily argue that it's not "best practice" in C#, but the risk involved is dramatically lower than in C++ as it only impacts the file or namespace scope where the directive is placed.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

Because C# has no free-standing functions.

The problem with using namespace std in C++ is when the compiler suddenly decides to call the std:: function instead of your function which is not surprising with names like count, distance or find being template functions that take just about anything.

This is much less of a problem in C# because C# does not have free-standing functions and it has stricter implicit conversions (e.g. you can't pass an int to a function that expects a pointer).

Sergey Slepov
  • 1,861
  • 13
  • 33