简体   繁体   中英

Namespace with same name as a class name

I thought the following makes sense to do, but it's not possible and an error will be thrown: The namespace 'foo' already contains a definition for 'bar' .

namespace foo
{
    public class bar { ... }
}

namespace foo.bar
{
    public class baz : EventArgs { ... }
}

What would be the appropriate way of namespace naming for a case like this?

You have to understand that in the context of the CLR, there is no such thing as a namespace. Namespaces are purely a language feature that exist only to simplify code so that we dont have to always read fully qualified class names always.

In your example,

namespace foo
{
    public class bar { ... }
}



namespace foo.bar
{
    public class baz : EventArgs { ... }
}

when this sourcecode is compiled, the the IL is not even aware that there are two namespaces - foo and foo.bar. Instead it only knows about the class definitions. In this case, when it comes across the class bar, it knows that you have a class called foo.bar

When it comes across the class baz, it resolves the full name of the class as foo.bar.baz

But if this were the case, baz should have been rightfully declared within the class definition of bar and not in a seperate namespace as you have done here.

You have to find another name for the namespace or the class name. There's no way around it.

Finding appropriate naming is difficult but can be done.

This really depends on what you are trying to achieve. If you really want baz to sit under the foo.bar namespace because it is dependent/closely linked you to bar can make it a child class of bar:

namespace foo
{
    public class bar 
    {
        public class baz : EventArgs { ... }
    }
}

You can now create a new instance as:

var test = new foo.bar.baz();

Within the same namespace it is not possible to have the same classname. If your namespaces look so much the same, you probably want them in the same namespace. If this is not the case you probably need to reconsider a logical classification of your classes within the namespaces.

may be

namespace foo_bar
{
    public class baz : EventArgs { ... }
}

Otherwise it is simply not possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM