Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle same class name in different namespaces?

I am trying to create a common library structure. I am doing this by creating separate projects for every common lib I want.

I have the following 2 namespaces: MyCompany.ERP and MyCompany.Barcode

I need both of them to have a class named Utilities and be static. If I do that I will then need to specify the full namespace name before my static class in order to access it.

Is there any other preferred way to do it?

Or I should go for different names in classes like BarcodeUtils and ERPUtils?

like image 398
e4rthdog Avatar asked Nov 12 '12 13:11

e4rthdog


People also ask

Can two namespaces have same name?

Absolutely nothing, as far as you avoid to use the using namespace <XXX>; directive. As David Vandevoorde said, the “fully qualified name” (the standard term for him “complete name”) is different, while you have to prefix the name with, <namespace>::, and compiler can make the difference between both.

Can a class have the same name as a namespace?

Inside a namespace, no two classes can have the same name.

Can partial classes be in different namespaces?

Partial class is only possible in same namespace and same assembly. Namespace could be in two different assemblies but partial class could not. Use partial keyword in each part of partial class. Name of each part of partial class should be the same but source file name for each part of partial class can be different.

Can a namespace have more than one namespace grouping?

You can have the same name defined in two different namespaces, but if that is true, then you can only use one of those namespaces at a time.


1 Answers

If i do that i will then need to specify the full namespace name before my static class in order to access it?

No, there is no need for that, though the details depend on the class that will use these types and the using declarations it has.

If you only use one of the namespaces in the class, there is no ambiguity and you can go ahead and use the type.

If you use both of the namespaces, you will either have to fully qualify the usages, or use namespace/type aliases to disambiguate the types.

using ERPUtils = MyCompany.ERP.Utilities; using BCUtils = MyCompany.Barcode.Utilities;  public void MyMethod() {   var a = ERPUtils.Method();   var b = BCUtils.Method(); } 
like image 58
Oded Avatar answered Oct 07 '22 02:10

Oded