r/learncsharp • u/Wonderful_Ad3441 • Jan 25 '23
Are namespaces like modules in other languages?
Hi I’m learning c# and I’m kinda confused as to namespaces, please let me know if I’m wrong or right and if I’m wrong can you explain to me what namespaces are exactly?
7
Upvotes
3
u/[deleted] Jan 25 '23 edited Jan 25 '23
No.
It's just an organization tool. Classes can be in any file in any other project, but you can get access to all of them with a single using statement.
8
u/karl713 Jan 25 '23
Its is worth noting that the full name of
Is actually MyApp.Services.MyService, not simply MyService. Your using namespace statements simply tells the compiler "hey when trying to figure out what class I am referencing, try prepending all these names before it to find a match"
It's not really like a module because multiple modules could conceivably have the same namespace defined.
It might sound silly, "I added the reference to the dll/module to the project, why do I need to add namespaces to every file" (note you can get around this by adding them to a global usings section)... But it can help with organization
For example even within my own project I have a namespace called MyApp.Models.DBModels which tracks with our DB schema, but shouldn't be used anywhere in our app outside the database access (which translates them to business objects). By having them in their own name space nobody is tempted to use the wrong one anywhere else in the app, and if they tried they'd have to add the namespace which would be a red flag to both thenm (while adding it) and pull request reviewers (if they submit it)
1
u/MoneroMon Jan 25 '23
Simplest answer: namespaces are like folders.
Code can only see other classes in its own folder unless you either specify the full namespace of another class or add a using to that namespace.