Bob
Bob

Reputation: 861

Namespaces in C# Same Project

I have a static class like so:

namespace Engine.Configuration
{
    public static class Configuration
    {
        public static int i;
    }
} 

In the same project, but a different namespace I have a class trying to access the static class variable:

namespace Engine.MainProgram
{
    public class MainProgram
    {
        int x;
        int y;
        public void LoadConfiguration()
        {
            x = Configuration.Configuration.i;
        }
    }
}

What I would like to do is just place a using statement in MainProgram like so:

using Engine.Configuration;
...
x = Configuration.i;

But when I try to visual studio always treats Configuration as a namespace instead of the static class. My question is why does this happen and how do I correct this?

Upvotes: 1

Views: 1126

Answers (2)

Mario S
Mario S

Reputation: 11945

The compiler doesn't always know how to distinguish between a namespace and a class name with the same name.

Change this:

using Engine.Configuration;

To a namespace alias:

using Configuration = Engine.Configuration.Configuration;

Explenation:

Let's say you are working directly under the root namespace, Engine, like so:

namespace Engine
{
}

Then you could get things in other namespaces like this:

namespace Engine
{
    Engine.Configuration.Configuration;

    // Or since you are in the root (Engine) you don't need to specify Engine:
    // You can always omit the root namespace if the namespace you're in has the same root.
    Configuration.Configuration;
}

Or by declaring a using for the namespace, but the compiler won't know if you mean the namespace or the class in the namespace:

using Engine.Configuration;

namespace Engine
{
    // This will still work.
    Engine.Configuration.Configuration;

    // This will break, do we mean "Engine.Configuration.Configuration" or "Engine.Configuration"?
    Configuration;
}

So it's a good practice to never have the same name for a class as the namespace it lives in. Maybe change the namespace to Engine.Configurations.

Upvotes: 1

Stephen Hewlett
Stephen Hewlett

Reputation: 2445

Try:

using A = Engine.Configuration;

then

x = A.Configuration.i;

or just use

x = global::Engine.Configuration.Configuration.i

Upvotes: 2

Related Questions