C# – Nested Classes or Namespace

cnamespacescope

Why do need namespaces when we have nested classes. What can be done through namespaces, can also achieved through nested classes.

so I don't understand the reasoning of having namespaces ?

Best Answer

Well, currently the main difference is a namespace is designed to be augmented in separate files. If you try to add a new nested class to a class, you get:

test1.cpp:3:7: error: redefinition of ‘class NamespaceClass’

However, it only works that way because it was defined that way. It wouldn't be that difficult to rework the compiler to append to a class in certain ways when it sees what is now a redefinition.

The reason they don't is that a namespace and a class are conceptually two different things, used for different reasons. A class is meant to be instantiated, and is used to create strong cohesion between a data structure and its associated methods. A namespace is meant to loosely gather modules to make it easier to share groups of several files without causing naming clashes.

Yes, you can approximate the behavior of one using the other, but that doesn't make them the same. If you used a redefinition-allowed class instead of namespaces, you would have problems like:

  • Having to look through all header files using that class to get its entire definition, including determining if it's instantiable or not.
  • Wanting to use a name that denotes its purpose as a namespace, like StdNamespace instead of just std.
  • Needing some sort of syntax to clue you in when you do accidentally redefine a class when the compiler just thinks you mean to augment it like a namespace.

When you add up all the special cases you would need to handle to make it truly follow the open-closed principle, you may as well just call it a namespace.