-1

I've have the following class

namespace COM.XX.ZZ{
 class XX{
 }
}

when I try to use it in a different class

using COM.XX.ZZ;
class someClass{
 static void main(String args[]){
       XX.someMethod();
 }
}

Visual studio get confused between the class and the package because both have the same name. Is it a known limitation of visual studio that namespace and class should always be different?

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
omer727
  • 7,117
  • 6
  • 26
  • 39
  • 1
    what error does it show ? – shujaat siddiqui Oct 07 '15 at 08:36
  • 1
    The fact that you have a class and namespace the same name is a bad design decision. Save yourself a lot of pain and change one or the other. A namespace should describe a general category/distinction e.g. `MyApp.Web.WebSockets`, that contains specific classes under that category e.g. `WebSocketFactoryThingy`. The name of a class shouldn't be part of the namespace in my opinion. But, that's just me. – Jason Evans Oct 07 '15 at 08:37
  • Which version of Visual Studio? – ΩmegaMan Oct 07 '15 at 08:38
  • XX.someMethod() is not static method (but you are calling that the way, you would call a static method), so I guess XX is an instance of class, right? – aniski Oct 07 '15 at 08:40
  • Define namespaces in *plural* form, and class names in *singular* form, and voila, the problem will go away. – Maarten Oct 07 '15 at 09:06
  • So basically it's a visual studio limitation – omer727 Oct 07 '15 at 13:52

2 Answers2

5

It isn't necessary to have separate class and namespace names, but indeed, the compiler gets confused sometimes. For all parties it is best to keep namespace names and class names separate.

If you do want to use the same name, you could help the compiler not get confused. Use a using for your class:

using XXClass = COM.XX.ZZ.XX;

Then you can use it like this:

XXClass.someMethod();

This is far from recommended, so I suggest to rename either of them.


Another reason this might fail is that someMethod isn't static. In that case the compiler thinks you are referring to XX-the-namespace. Try to instantiate XX first:

XX xx = new XX();
xx.someMethod();
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

If your class has static method, called SomeMethod(), which is accessable, such as:

namespace COM.XX.ZZ
{
    class XX
    {
        public static void SomeMethod()
        {

        }
    }
} 

Than you can use it:

using COM.XX.ZZ;

class someClass
{
    static void main(String args[])
    {
       COM.XX.ZZ.XX.SomeMethod();
    }
}

note that, I've added the full namespace prefix before calling the static method.

Edit: using the same name for namespaces and classes is really not a good idea.

aniski
  • 1,263
  • 1
  • 16
  • 31