When you create a new class in visual studio it includes a namespace definition which is pulled from the default namespace set in the project properties. However if you remove the namespace definition it picks up the default namespace anyway. Is it safe to remove and is there any benefit to leaving it there?
views:
228answers:
4It does not pick up the default namespace, in general. In general, it puts it into the global namespace, which is not the same thing.
If you want the class to be in a namespace, then leave the namespace
in place.
In VB context, it is safe, but a good rule of thumb is that "explicit is better than implicit". Personally, I've always found VB implicit namespace and imports to be a good example of misfeatures that hamper code readability more than they help conciseness. But, of course, it is very subjective.
Theoretically it's possible and legal, but... it's just not nice :) (in 99% cases). When you are writing your code, it's nice to "pack" it inside some namespace.
Also, you won't have problems with name conflicts (fe. 2 classes with identical name - legal and manageable if you will have them in separate namespaces.
Basically:
1. Having stuff in global namespace isn't nice (it's not the same as "default" namespace)
2. Namespaces allow you to easier manage your code (and this is a benefit of leaving even the default namespace instead of removing it)
3. Namespaces help to resolve name conflicts etc.
In c# the class does not automatically use the default namespace but instead will reside in the global namespace which is generally not recommended.
In VB.NET the class will automatically use the default namespace and not the global namespace and is safe however this is not the best practise. As Pavel Minaev mentions below...
In VB context, it is safe, but a good rule of thumb is that "explicit is better than implicit". Personally, I've always found VB implicit namespace and imports to be a good example of misfeatures that hamper code readability more than they help conciseness. But, of course, it is very subjective.