For example, I name my file(console application) 'Hello', so do I have to write namespace Hello?If no, what is the purpose of adding namespace?
No, the namespace can be anything, they don't have to be the same as the filename. It is good practice to have the namespaces correspond to physical file paths (folders in your solution).
So if you have a file in .\Interfaces\ViewModels\Client, usually the namespace declaration in that file will be:
namespace DefaultNamespaceOfAssembly.Interfaces.ViewModels.Client { ... }
ReSharper even offers to fix up namespaces that are breaking this rule.
The purpose of the namespace is to
modularize your code by putting things that belong together (by functionality for example) in the same namespace,
reduce name collisions. Without namespaces importing an external library would result in hell if it were to contain classes with the same name as classes in your own code.
Probably there are more, but at first thought these come to mind, although these two should already be enough to justify their existance.
I name my file(console application) 'Hello', so do I have to write namespace Hello?
No, you can name it whatever you want.
If you're writing a library to be used by other code, and that library is the only (or main) source of types in that namespace, then it would be convenient to users for the DLL to have a name based on the namespace, because then they can easily remember that the UsefulTypes.CoolStuff classes all come from the UsefulTypes.CoolStuff.dll assembly. There's no rule that you have to do this, it can just be convenient if you do.
With applications this isn't anywhere near as useful; end-users don't care what namespaces you use and may not know what a namespace is. It might be useful if the application was a tool for .Net developers, but otherwise not.
If no, what is the purpose of adding namespace?
Exactly what it says; it's a space for names. By putting the names of classes, enums, delegates and structs into a namespace they are separated from other cases of the same name being used in other namespaces. You don't have to make sure that no library you used has something with the same name, unless you are actually going to use that thing with the same name.
When writing an application it keeps stuff from other assemblies out of your way. When writing libraries it's even more important, as it also keeps your stuff out of other people's way.
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