Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespace with same name as a class name

Tags:

c#

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?

like image 791
user247702 Avatar asked Oct 17 '11 12:10

user247702


People also ask

Can namespace and class have same name?

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

Is namespace same as class?

Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention.

What are the two types of namespaces?

When creating a namespace, you must choose one of two namespace types: a stand-alone namespace or a domain-based namespace. In addition, if you choose a domain-based namespace, you must choose a namespace mode: Windows 2000 Server mode or Windows Server 2008 mode.


2 Answers

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.

like image 99
gprasant Avatar answered Sep 16 '22 12:09

gprasant


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.

like image 40
Candide Avatar answered Sep 20 '22 12:09

Candide