Home > Enterprise >  C# Namespace naming conventions for extensions of existing libs
C# Namespace naming conventions for extensions of existing libs

Time:03-28

I'm using open-source library in my project and I have an idea how to extend it. But if I ever publish it someday, I want to be correct with namespace names. I've checked docs with naming conventions, but none of them describes, how to name namespaces for extensions of existing libraries.

For example, I'm extending SomeLibrary. It has namespace SomeLibrary.Types, which I want to extend, by adding some of my types to it. So the question is: how should I name namespace in my project?

Can I use SomeLibrary.Types namespace? Is it correct to use other's namespaces or should I distinguish my library namespaces from the namespaces of the library I extend? I've seen that some libs, that extend existing ones, use the same namespaces, like Microsoft.EntityFrameworkCore.InMemory uses Microsoft.EntityFrameworkCore namespace for it's UseInMemoryDatabase method, but I don't think this is a good example.

If I shouldn't name so, could you please suggest, how I should name namespaces in projects, that extend existing ones?

CodePudding user response:

There are a few articles on namespace guidance and best practices. Best practices are opinions and do change over time.

Let's start with the bit about you having open-source in your project that you see will eventually be extended.

  1. If at all possible, don't extend it. It's open source and that allows you to do a couple things before considering extending. First, if the feature you are writing for the open source makes sense, you could contribute to it. Second, you could fork the repository and maintain your own copy with the feature you added.

  2. If you must extend it, it should be packaged and distributed as a NuGet package. Here's some guidance on open-source libraries in general. One thing I didn't see in there was consider using the same license for your code as the code you're extending. And here is some more detail on the namespace guidance if you go this route.

Noteworthy for this case:

✔️ DO prefix namespace names with a company name to prevent namespaces from different companies from having the same name.

❌ DO NOT give the same name to types in namespaces within a single application model.

The one bit you left out is whether you are extending with instance types, like a class or implementation of an interface or with extension methods. It makes a bit of a difference.

This article from Microsoft Docs has some guidance that is geared towards extension methods

❌ DO NOT put extension methods in the same namespace as the extended type unless it is for adding methods to interfaces or for dependency management.

✔️ CONSIDER defining extension methods in the same namespace as the extended type if the type is an interface and if the extension methods are meant to be used in most or all cases.

  • Related