C# class in a directory without having the directory name in its namespace
If you add a directory in your Visual Studio project and you add a class
inside it, the namespace
will respect the whole path the directory inclusive.
But sometimes, I prefer having the class in the main project namespace, although it lies in a directory structure, just because I don't want to have mess in my code.
So often happens that I rewrite the Myproject.MyDirectory
namespace to be Myproject
only.
Is it OK in your opinion? Or does 开发者_运维百科any convention say that every class inside the directory must have it included in the namespace ?
Thanks
There isn't any convention restricting from what you're trying to do. I usually have multiple directories in my project to organize class files and use different namespaces with no respect to the directory structure and I don't have any problems.
In my view, folders and namespaces serve for different purposes.
Folders are useful to provide a clear hierarchy for people who read your code
Namespaces are useful to provide a clear hierarchy for people who use your code. E.g. calling the API provided by your code, when they don't see the actual source code.
Therefore, inconsistency is perfectly fine, as long as each makes sense.
There is no constraint, but some think it's useful to have the namespace identical to the path. So you could choose any namespace and place the class file wherever you want.
精彩评论