Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper C# namespace usage?

Tags:

namespaces

c#

I come from a Java background, and I see a lot of people say namespaces = packages, but looking around at available code it doesn't seem to me that people use namespaces like they used packages.

Currently I'm working on a DLL to manage all my data access to a database to be shared between two Windows Applications. So far I have been creating packages like I would for Java so I have a Domain, Services, DAO (I call it Repositories) sub namespaces off my top level. Is this correct? Has anyone written a best practice for namespaces? I assume this is probably a very minor point, but I don't want to go off going against the grain so to speak.

like image 648
Patrick McDaniel Avatar asked Dec 09 '22 13:12

Patrick McDaniel


1 Answers

Slightly subjective, there is no "definitive, correct" answer to this.

Here's how i do it, with the intention that assemblies can be shared amongst projects.

Consider i have a company name called FooBar (+1 for originality anyone? :)

All your assemblies start from this root namespace. We have many shared assemblies.

Things like:

  • MVC (UI) HTML Helpers. These go in one assembly.
  • Generic Repository. Repository pattern implemented with generics, for re-use.
  • LINQ Extension methods (paging, general syntactic sugar factory). Again, these go in one assembly.

So, our FooBar Namespace Universe might look like this:

FooBar
|
 ---- FooBar.Common.Mvc
|
 ---- FooBar.Common.DataAccess
|
 ---- FooBar.Common.Linq
|
 ---- FooBar.ProjectOne (ASP.NET MVC Web Application)
|     |
|      --- FooBar.ProjectOne.Repository (makes use of FooBar.Common.DataAccess)
|     |
|      --- FooBar.ProjectOne.WebMvc (makes use of FooBar.Common.Mvc)
|
 ---- FooBar.ProjectTwo (WPF Application)
      |
       --- FooBar.ProjectTwo.Repository (makes use of FooBar.Common.DataAccess)
      |
       --- FooBar.ProjectTwo.BindingServices (makes use of FooBar.Common.Linq)

Know what i mean?

Setup your namespaces in a way that it 'feels right' putting common logic into common areas, based on the heterogeneous namespace.

You'll find a lot of companies with multiple shared projects follow this trend.

Your thinking of 'sub-namespaces' is correct (in my opinion).

like image 162
RPM1984 Avatar answered Dec 25 '22 15:12

RPM1984