Can someone explain the nesting in C#? You have a namespace. Inside the namespace, you have a class. Then, inside this class, you have the main function. Why is it set up this way. Are all classes supposed to be ouside this namespace? When would you onclude a class inside this namespace?

Recommended Answers

All 2 Replies

Look,
Nested namespaces: used collect all related-functionality classes inside a parent namespace like

namespace System
{
class string...
class int...
class .....
namespace IO
{
class File...
class Stream....
class .....
}
}

Class inside class to limit the functionality of nested class to the parent class as you don't need your assembly or your nested class namespace classes to use nested class functionality (in short: more encapsulation)

Class outside namespace, won't be used except your assembly. (Don't know why some developers do that!!! as you can flag your class with internal keyword)

Any questions?!

The main reason for enforcing the namespaces is to not pollute the naming scope and to keep the code better organized.

In C, for example, there are neither classes nor namespaces. This means any function has to have a unique name and you can easily end up with a bunch naming conflicts.

In C++, there are classes, which help alleviate a small bit of the problem (as related operations are grouped together), and there are namespaces as well. The namespaces allow you to group classes in a more logical manner. For instance, variations of a vector class can represent a 2D vector, a 3D vector, or an alternative to an array. Since the names for all 3 of these would conflict, with namespaces we can still call each class vector but have them reside in different naming scopes. C++, however, doesn't strictly enforce a namespace structure, so if you create a class named string and put it in the global scope, then it will have a name conflict with any other class named string in the same scope.

C# makes you put your code in namespaces to avoid global type name conflicts. This doesn't totally eliminate the conflicts though, because you can bring whole namespaces into scope with the using clause. When that happens, you need to refer to the classes by Namespace.ClassName to distinguish between them.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.