Christoffer Reijer
Christoffer Reijer

Reputation: 1985

Name conflict between namespace and class

I have a structure with several namespaces, and in each namespace I have one static class that is sort of a small, little spider in the net of that namespace. Like the head of the department.

Let's take an example of two namespaces, Foo.Bar.Baz and Foo.Bar.Quux.

I have one file which looks like this:

namespace Foo.Bar.Baz
{
  static class Baz
  {
    public static void DoSomething()
    {
      Console.Writeline("Doing something...");
    }
  }
}

And then a second file:

using Foo.Bar.Baz
namespace Foo.Bar.Quux
{
  static class Quux
  {
    public static void GetToWork()
    {
      Baz.DoSomething();
    }
  }
}

Now, I get an error in the second file when I try to compile because it thinks that Baz is the namespace and not the class. But since I have the line using Foo.Bar.Baz it should be fine to use any class inside that namespace without needing to prefix it with the name of the namespace, right? I can use other stuff from that namespace correctly, but not a class with the same name.

It kinda feels like the compiler secretly adds this line to every file: using Foo.Bar.

Also, I cannot just put the static Baz class inside the Foo.Bar namespace since then I will get errors saying that Foo.Bar.Baz is not a namespace (since I have other stuff in that namespace and have files that use that namespace). Then it seems the compiler sees the static class and decides that Foo.Bar.Baz is a static class and not a namespace.

Of course, I could just rename the static classes to something like Manager but then I would still have to spell out the full Baz.Manager.SomeMethod and Quux.Manager.SomeMethod in files that need to access stuff from both namespaces. This feels rather clumpsy, I'd rather just have it be Baz.SomeMethod and Quuz.SomeMethod.

Any ideas?

Upvotes: 1

Views: 2154

Answers (2)

Channs
Channs

Reputation: 2101

Since Baz is a static class, it cannot contain instance members. So, DoSomething() must be declared as a static method.

Once you have this, you can either do this:

using Foo.Bar.Baz;

public void GetToWork()
{
    Baz.Baz.DoSomething();
}

or this:

using baz = Foo.Bar.Baz.Baz;

public void GetToWork()
{
    baz.DoSomething();
}

However, I do agree with the comments in your question that using the same name for the namespace (logical container for a set of classes) and its containing class (encapsulates data and behavior) may result in readability / maintainability issues.

Upvotes: 0

Dethariel
Dethariel

Reputation: 3614

Maybe this can help:

using Baz = Foo.Bar.Baz.Baz;

Upvotes: 1

Related Questions