简体   繁体   中英

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.

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.

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. Eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM