Namespace with the same name as the class name

I thought the following made sense, but this is not possible and an error will be generated: 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 namespace namespace method for this type?

+6
source share
5 answers

It really depends on what you are trying to achieve. If you really want bas to sit in the foo.bar namespace because it depends / is closely related to you, you can make it a child class of bar:

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

Now you can create a new instance as:

 var test = new foo.bar.baz(); 
+4
source

You should understand that in the context of the CLR there is no such thing as a namespace. Namespaces are just a language function that exists only to simplify the code, so we don’t always have to read fully qualified class names.

In your example

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

when this source code is compiled, IL does not even know that there are two namespaces - foo and foo.bar. Instead, he only knows class definitions. In this case, when it gets into the class panel, it knows that you have a class called foo.bar

When it comes to the baz class, it resolves the fully qualified class name as foo.bar.baz

But if so, baz should have been fairly declared in the class definition of bar, and not in a separate namespace, as you did here.

+7
source

You need to find another name for the namespace or class name. There is no way around this.

Finding the right naming convention is difficult, but it can be done.

+4
source

It is not possible to have the same class name in the same namespace. If your namespaces look the same, you probably want them to be in the same namespace. If this is not the case, you will probably need to rethink the logical classification of your classes in namespaces.

+1
source

may be

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

Otherwise, it is simply impossible.

0
source

Source: https://habr.com/ru/post/899459/


All Articles